0
votes

in my controller parameter passed to posts function in user model with construct method . i want the users that have posts and posts should be according to the parameter.

class MyController extends Controller
{
    private $user;
    public function __construct(User $getuser)
    {
        $this->user = $getuser;
    }
    public function index($id = 2)
    {
        $posts = $this->user->posts($id);
        $user = User::whereHas('posts')->find($id);
        return $user;
    }
}

in my user model parameter accessed and passed to relationship .

class User extends Authenticatable
{
    use Notifiable;
    
    protected $fillable = [
        'name', 'email', 'password',
    ];

    function posts($id)
    {
        return $this->hasMany('App\Post')->where('id',$id);
    }
}

it works when use like this

"return $this->hasMany('App\Post')->where('id',1);"

but not working with passed parameter. getting this error

"Symfony\Component\Debug\Exception\FatalThrowableError Too few arguments to function App\User::posts(), 0 passed in C:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php on line 415 and exactly 1 expected"

1

1 Answers

0
votes

You're making life difficult for yourself and not allowing the framework to do the heavy lifting.

web.php

Define a route that accepts a User identifier

Route::get('/users/{user}', 'UserController@show');

User.php

public function posts() {
    return $this->hasMany(App\Post::class);
}

UserController.php

public function show(User $user) {
    return view('users.view', compact('user');
}

resources/views/users/view.blade.php

ddd($user->posts);