Skip to content
Advertisement

How to use print all comments for respective posts using relationship in Laravel 8

I am trying to print all comments per post using the relationship,

Error: Property [comments] does not exist on the Eloquent builder instance.

Post Model

  class WorkTravel extends Model
{
    use HasFactory;

    protected $table = 'work_travel';

    protected $fillable = ['name', 'role', 'location','salary','application_deadline','position','description'];


    public function comments()
    {
        return $this->hasMany(CommentWorkTravel::class);
    }

}

Comment Model

class CommentWorkTravel extends Model
{
    use HasFactory;

    protected $table = 'comments_for_work_travel';

    protected $fillable = ['message'];

    public function workTravel()
    {
        return $this->belongsTo(WorkTravel::class);
    }

}

Controller

    public function index(){

    $work_travels=WorkTravel::select('id','name','role','application_deadline')
        ->comments()
        ->paginate(6);

    dd($work_travels);
//Error: Call to undefined method DatabaseEloquentBuilder::comments().

Advertisement

Answer

The error

Property [comments] does not exist on the Eloquent builder instance.

indicates that you are trying to recieve a value from something that is not a model instance.

See your line

$work_travels=WorkTravel::select('id','name','role','application_deadline')
    ->comments
    ->paginate(6);

You are selecting a row of type “WorkTravel” and than calling for the property “comments” (without () at the end). But what you get there is the relation defined in the model, not the result of a query with that relation.

It works like this

Model->relationshipmethod()->where('something,'searchvalue')->get()

or

Model->relationshipmethod()->all()

if you want to use the rows for a paginated table laravel also offers the paginate method which will recieve a subset of the rows and attach information for getting the previous and next page to the collection returned.

Model->relationshipmethod()->paginate()

To test that you should modify your statement to use the real model and a relationship method defined in that model. Not the select method

$WorkTravelID = 1; // get that from somewhere
$WorkTravel = AppModelsWorkTravel::find($WorkTravelID);
$work_travels = $WorkTravel->comments()->paginate(6);
dd($work_travels);

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement