laraveleloquenthas-manyisnull

Laravel - Eloquent relations and variables


I have 2 tables , connected by 'company_name' through $this->hasMany method.

table 'Companies' -> 'company_name', 'logo', 'description';
table 'Branches' -> 'company_name, 'type', address', 'phone';

So in my view, I display the info from the first table, AND if the company has branches, I display them too. Everything works alright until there. My problem arrives with the 'type' column.

@If the type of the company is for instance '1' , I display a certain text.

So the thing is that if a company has no branches, the view gives an error (Trying to get property 'type' of non-object)...

I have researched but I really don't know how to solve it.

This is in my controller method:

$company = Company::where('slug', $slug)->first();
$branch = $company->branch->first();

return view('companies.show', compact('company', 'branch'));

I know that I should declare $branch only if that company exists on the table 'branches', but don't know really how to. Thanks in advance if someone gives me a hand with this.


Solution

  • You should check in the view if the variable is an object before attempting to access its properties. In your case, $branch can either be an object or NULL.

    You can print its value using the following expression:

    {{ isset($branch) ? $branch->type : '' }}
    

    Alternatively, you can use a more concise version of the same expression using the null coalescing operator:

    {{ $branch->type ?? '' }}