laravellaravel-4laravel-blade

Laravel - How to a try/catch in blade view?


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

Solution

  • 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' }}