I would like to create a way to compile in a view, the try/catch. How can I do this in Laravel?
Example:
@try
<div class="laravel test">
{{ $user->name }}
</div>
@catch(Exception $e)
{{ $e->getMessage() }}
@endtry
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' }}
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
while i agree with @areed that something is wrong if you have to use a try...catch, there are weird cases where a wrong approach can lead you down that path. One instance is using the same blade to house a paginate()
and a get()
response. Well, this might help a little.
<?php try{ ?>
//try to show something
{{ $products->links() }}
<?php }catch(\Exception $e){ ?>
// show something else
<?php } ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With