PHP Code Inside a Laravel 5 Blade Template

PHP code inside a Laravel 5 blade template

According to documentation, in Laravel 5.2 and newer you can use the following code:

@php
{{-- PHP code here --}}
@endphp

Alternatively, you can extend the Blade templating engine as it's described here.

If neither of the above solutions is suitable, you are stuck with the answers given by Armen and by Gonzalo.

How to write PHP code inside blade template

First of all, You should not put DB query code in your blade.

Now, when you run a query using eloquent and call get(), the response is a Collection::class instance that can be treated as an array but cannot be automatically transformed into a number/string.

If you only need the value of on field for one entry, use value() instead.

$amount_to_be_collected = DB::table('shipments')
->where('mission_id', $mission->id)
->value('amount_to_be_collected');

Php code in laravel blade php

Instead of:

<?php echo $_GET["tname"]; ?>

just use:

{{ request()->input('tname') }}

You should not use PHP code in Blade even you can use @php ... @endphp directives

Comment in .blade.php template

In blade syntax, a comment starts with {{-- and ends with --}}

{{-- this is a comment --}}

But to comment out multiple lines, use standard PHP block comments instead, like:

<?php /* 
@if ($condition)
{{ HTML::form("foo") }};
@endif
*/ ?>

And never nest Blade and/or PHP code inside of Blade comments.

See also stackoverflow.com/Why Blade comment causes page to crash?



Related Topics



Leave a reply



Submit