How to get data from related table in Laravel (one to many)?
In Order model you need to use the belongsTo
relationship:
public function user()
{
return $this->belongsTo("App\User"); // second and third arguments are unnecessary.
}
In User model you can use hasMany relationship, for example in:
App/User.php
Add
public function orders()
{
return $this->hasMany("App\Order", "user_id", "id");
}
Now you can use this:
return User::find(1)->orders;
If you want to retrieve the all the Orders belonging to the current user, try using 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 would also need to change the hasOne()
to belongsTo()
in Order Model. See following (copied from @Martin Heralecký answer)
public function user(){
return $this->belongsTo("App\User");// second and third arguments are unnecessary.
}
Why belongsTo():
has_one
and belongs_to
generally are same in a sense that they point to the other related model. belongs_to
make sure that this model has the foreign_key defined. has_one
makes sure that the other model has_foreign key defined.
Your $orders
array will look something like this:
User => [
id => 'user id',
name => 'user name'
orders => [
0 => [
//order data
]
1 => [
//order data
]
.
.
.
.
]
]