I have a laravel crud with relations. but when i want to load the page some table rows dont have a value. and this gives the error: ‘Attempt to read property "name" on null’
But how do i ignore this message and keep loading in the page?
index.blade:
@foreach($files as $file)
<tr>
<td>{{$file->id}}</td>
<td>{{$file->title}} </td>
<td>{{$file->description_short}} </td>
<td>{{$file->description_long}} </td>
<td>{{$file->file}}</td>
<td>{{$file->language->name}} </td>
<td>{{$file->subfolder->name}} </td>
<td>{{$file->role->name}} </td>
<td>
<a href="{{ route('admin.file.edit',$file->id)}}" class="btn btn-primary">Edit</a>
</td>
<td>
<form action="{{ route('admin.file.destroy', $file->id)}}" method="post">
@csrf
@method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
controller:
public function index()
{
$files = File::with('subfolder', 'language', 'tag')->get();
$languages = Language::all();
$tags = Tag::all();
$subfolders = Subfolder::all();
$users = User::all();
return view('admin.file.index', compact('files', 'languages', 'tags', 'users', 'subfolders'));
}
i want the index to ignore all the NULL properties
4
Answers
Using the
@
before your php Variable will work for you like below.And also, by using
Note:
When you use
@
to the variable{{@$file->language->name}}
, we’re skipping the error message. This means we’re telling Laravel to "Leave this Variable alone". And It’s not the best way to check if emptyThere are various ways:
Error control operator:
@$file->language->name
the@
operator suppress the errors messages (imho not very clean 🙂 , but same result)From documentation:
Classical ternary operator way
$file->language ? $file->language->name : null;
From PHP7+ : Null Coalescing Operator
$file->language->name ?? null;
From PHP8+ : null safe Operator
$file->language?->name;
(amazing! :-))Laravel has a built-in helper for this, called
optional()
.https://laravel.com/docs/9.x/helpers#method-optional