How to get data from a linked table in Laravel (one to many)?

I have two tables: users , orders . I am trying to get all orders for the current user.

 Users Orders _____ ______ id | name id | user_id 

User Model:

 public function orders(){ return $this->hasMany("App\Order"); } 

Order Model:

 public function user(){ return $this->hasOne("App\User", 'user_id', 'id'); } 

Request in the controller:

 public function index() { $orders = Order::where('user_id', Auth::guard('api')->id())->get(); return response()->json( $orders->user ); } 

I get a NULL result, I am doing something wrong, because both tables have related rows.

+5
source share
3 answers

If you want to receive all Orders belonging to the current user, try using the following function.

 public function index() { $orders = Auth::user()->with('Orders')->get()->toArray();//To get the output in array /* ^ ^ This will get the user | This will get all the Orders related to the user*/ return response()->json($orders); } 

As pointed out by @Martin Heralecký, you also need to change hasOne() to belongsTo() in the Order Model. See Next (copied from @Martin Heralecký answer)

 public function user(){ return $this->belongsTo("App\User");// second and third arguments are unnecessary. } 

Why applyTo ():

has_one and belongs_to are usually the same in the sense that they point to another related model. belongs_to make sure that this model has the value foreign_key. has_one ensures that another model has a file_key.

Your $orders array will look something like this:

 User => [ id => 'user id', name => 'user name' orders => [ 0 => [ //order data ] 1 => [ //order data ] . . . . ] ] 
+1
source

In the order model, you need to use belongsTo relation:

 public function user() { return $this->belongsTo("App\User"); // second and third arguments are unnecessary. } 
+1
source

In the user model, you can use hasMany relationships, for example (in the /User.php application):

 public function orders() { return $this->hasMany("App\Order", "user_id", "id"); } 

Now you can use this:

 return User::find(1)->orders; 
+1
source

All Articles