Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 421
Wallace Maxters Avatar asked Jul 14 '15 15:07

Wallace Maxters


3 Answers

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' }}
like image 120
Martin Bean Avatar answered Oct 12 '22 10:10

Martin Bean


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
like image 25
Alan Reed Avatar answered Oct 12 '22 11:10

Alan Reed


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 } ?>
like image 2
Benjamin Ini Avatar answered Oct 12 '22 12:10

Benjamin Ini