19

Is there a way to retrieve all the records which has not null using eloquent model.

e.g.

I have relation setup

Plate model

public function project()
{
    return $this->hasOne('App\Models\Project');
}

project model

public function plate()
{
    return $this->belongsTo('App\Models\Plate');
}

How can I retrieve all the records which have value.

trying this return $p = \App\Models\Plate::with('project')->get();

will return everything, even those who have NULL.

enter image description here

All I want is plates which have projects attached to. I tried laravel documentation, but could't find anything. Is there also same approach for many relations

2
  • Don't forget you need plate_id column in your projects table to store the association Nov 17, 2015 at 14:48
  • @daveyWavey Thanks for reply! I do not want to store anything for now. All I want is to retrieve all the plates which have porjects attached to it. and not NULL Nov 17, 2015 at 14:55

1 Answer 1

62

You can use the has method to only retrieve plates that have a project.

\App\Models\Plate::with('project')->has('project')->get();

Docs on has: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.