Trying to get name of Reviewer from Product Review Eloquent in laravel

Viewed 202

In Product.php

public function reviews(){
    return $this->hasMany(Review::class);
}

In Review.php

public function product(){
    return $this->belongsTo(Product::class);
}

public function user(){
    return $this->belongsTo(User::class);
}

In User.php

public function reviews(){
    return $this->hasMany(Review::class);
}

in controller

$product = Product::where('slug', $request->slug)->with('category')->with('reviews.user')->first();

in Blade

{{$review->user->name}}

Now In blade it returns null.

mention that review table has product_id, reviewed_by

Now, How Can I get Reviewers Name from this relationship Models? Please Help me with this one.

3 Answers

first, you should fix you relationship:

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

you can ignore second argument only if you follow the convention (if your column name is user_id, not reviewed_by)

then in your controller:

$product = Product::where('slug', $request->slug)->with(['category','reviews'=>function($query){
$query->with('user');}])->first();

You need to specify foreign keys on both hasMany and belongsTo relations if you have different foreign keys other than laravel's default alphabetical order

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

//In User Model
public function reviews()
{
    return $this->hasMany(Review::class,'reviewed_by');
}

//In Product Model
public function reviews()
{
    return $this->hasMany(Review::class,'product_id');
}

You need to specify the foreign key to use for user, since it is not stored as user_id. Like so:

public function user(){
    return $this->belongsTo(User::class, 'reviewed_by');
}
Related