Question

I want to only retrieve a model(s) when they have a specific related model present e.g.

$posts = Post::has('comment')->get();

that works fine although the opposite does not:

$comments = Comment::has('post')->get();

I get the following error:

Has method invalid on "belongsTo" relations.

Basically the reason i want to do this is that in exceptional circumstances there are cases that when i call a related model in a view, that model may not have a related model present (even when it should) sometimes due to bad data in the database etc....

{{ $jobApplication->job->title }}

obviously gets the following error when that jobApplication has no job:

Trying to get property of non-object
Was it helpful?

Solution

That happens cause, when you have a 1->n relation on your database, the n part may has more than one register related to it. But, ain't the same the other way around. A post may have n comments, but a comment belongs to only one post. So, the method has('model') doesn't apply to this cases.

The solution for you problem, though, would be veirify if the variable is set. Try to do this on the controller.

Hope it help!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top