Wallace Vizerra
Wallace Vizerra

Reputation: 3542

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

Upvotes: 16

Views: 23832

Answers (3)

Benjamin Ini
Benjamin Ini

Reputation: 195

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 } ?>

Upvotes: 5

Martin Bean
Martin Bean

Reputation: 39389

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

Upvotes: 20

Alan Reed
Alan Reed

Reputation: 503

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

Upvotes: 18

Related Questions