Laravel - How to a try/catch in blade view?
You are probably doing something wrong if you need a try..catch
in your view. But that does not mean you should never do it. There are exceptions to every rule.
So anyway, here is the answer:
Put raw PHP in your view by using <?php ?>
or @php @endphp
tags. Then put your try..catch
in the raw PHP.
@php
try {
// Try something
} catch (\Exception $e) {
// Do something exceptional
}
@endphp
You should not have try
/catch
blocks in your view. A view is exactly that: a representation of some data. That means you should not be doing any logic (such as exception handling). That belongs in the controller, once you’ve fetched data from model(s).
If you’re just wanting to display a default value in case a variable is undefined, you can use a standard PHP null coalescing operator to display a default value:
{{ $user->name ?? 'Name not set' }}