Laravel getting value from another table using eloquent

We Are Going To Discuss About Laravel getting value from another table using eloquent. So lets Start this Laravel Article.

Laravel getting value from another table using eloquent

How to solve Laravel getting value from another table using eloquent

In Product Model write this code
public function category() { return $this->belongTo(Category::class,'category_id'); }
In Category Model
public function user() { return $this->belongTo(User::class,'user_id'); }
Now you can get product with category and user.
$product = Product::with('category.user')->whereRelation('category','user_id',2)->first(); $product->category->name; // get category name $product->category->user->name; // get user name

Laravel getting value from another table using eloquent

In Product Model write this code
public function category() { return $this->belongTo(Category::class,'category_id'); }
In Category Model
public function user() { return $this->belongTo(User::class,'user_id'); }
Now you can get product with category and user.
$product = Product::with('category.user')->whereRelation('category','user_id',2)->first(); $product->category->name; // get category name $product->category->user->name; // get user name

Solution 1

In Product Model write this code

public function category()
{
    return $this->belongTo(Category::class,'category_id');
}

In Category Model

public function user()
{
    return $this->belongTo(User::class,'user_id');
}

Now you can get product with category and user.

$product = Product::with('category.user')->whereRelation('category','user_id',2)->first();
$product->category->name; // get category name
$product->category->user->name; // get user name

Original Author Chando Of This Content

Solution 2

You can check this link that help me for that:

User::where('id', $x)->with(['category.product'])->first();
//or
User::with(['category.product'])->find($x);

Presuming you already have relation in user.php

public function category()
{
    return $this->belongTo(Category::class,'category_id');
}

in category.php

public function user()
{
    return $this->belongTo(User::class,'user_id');
}

Original Author Puneet Sharma Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

ittutorial team

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment