Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two tables: users, orders. I try to get all orders for 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');
}

Query in controller:

public function index()
{

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

I get NULL result, I do something wrong, because there are related rows in both tables.

like image 598
Dev Avatar asked Jul 18 '16 21:07

Dev


People also ask

What is many to many relationship in laravel?

In the category_product table, you can see product_id 1 have multiple entiries with category_id 2 and 3. That's how you can create many to many relationships in Laravel Eloquent. Obviously, you can use the inverse of this relationship to attach a category to multiple products.

What is belongsTo in laravel?

A belongsTo() relationship matches a related table's 'id' to a 'localKey' field on 'this' model. Another way to think about it is the belongsTo() relationship should live on the model that has the field that links to the related tables id.

What is pivot table in laravel?

The pivot table in laravel is a structured value that is grouped and aggregated in the individual items where the extensive table is obtained or accessed in the form of a spreadsheet, database, or other discrete functions.


1 Answers

If you want to retrieve all the 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 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 the same in the 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
       ]
       .
       .
       .
       .
   ]
]
like image 52
jaysingkar Avatar answered Sep 18 '22 01:09

jaysingkar