There is a controller method that outputs posts according to specified conditions. Several purchases can be attached to each post, in the purchase model are sorted by id and the last one is displayed in view

Model Posts :

class Posts extends Model { public function user(){ $this->belongsTo('App\User', 'id', 'user_id'); } public function purchases() { return $this->hasMany('App\Purchase', 'post_id', 'id')->orderBy('id', 'desc'); } } 

and Purchases model

 class Purchase extends Model { public function posts() { return $this->belongsTo('App\Posts','id'); } public function user() { return $this->hasOne('App\User','id', 'user_id'); } } 

The Purchases model has a user_id field, that is, the id of the user who made the purchase. I need to transfer data about the user who bought it to the view through this controller function:

  public function sold(){ $post=Posts::where([ ['amount', '=', 0], ['user_id','=', Auth::user()->id] ])->with('purchases')->paginate(5); return view('SoldItems')->withPost($post); } 

How can I do this better?

    1 answer 1

    In the Posts model, try to register like this

     class Posts extends Model { public function user(){ $this->belongsTo('App\User', 'id', 'user_id'); } public function purchases() { return $this->hasMany('App\Purchase', 'post_id', 'id')->orderBy('id', 'desc')->with("user"); } }