Blade - using conditionals on a relationship that can return null.
So I ran into a templating issue with Blade last night and was hoping for some help…
Here is a quick synopsis:
I have a template that needs to show and hide a section based on a conditional of a relationship… To keep it simple, I’m going to relate this to a Task app…
First, here is the controller:
$project = Project::with(’tasks')->findOrFail($id);
return view('projects.tasks', compact('project'));
When no tasks are present, it obviously returns a null value - expected.
Now the template it self needs to show a a button if no value is assigned to the task upload, as an example:
{{ $project->tasks->uploaded_document }}
In the template, I need to show an hide a button based on that condition (is there a document?), easy right? So I tried this:
@if(is_null($project->tasks->uploaded_document))
// show the upload a document button
@else
// show the link to the document
Pretty straight forward with a seeded database… Then the tricky part comes along… What happens when the he `t relationship is null? This error is thrown, and for good reasons…
Trying to get property of non-object
Because the tasks relationship is null… So there is my predicament, I can’t really change the template design - not my call. So, I’m sure there is a better way to handle this.. Anyone want to give it a go?
Please or to participate in this conversation.