Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why shortcode @php() interfere with @php and @endphp

I am looking for a reason why in blade files (Laravel) code with mixed @php() and @php ... @endphp fails, and works fine with consistent usage of those codes across the file. I’ve just learned that the hard way but can’t find the reason.

Fails:

@php($foo = 'foo')
<h1>{{ $foo }}</h1>
@php
    $bar = $foo . 'bar';
@endphp
@for($i = 1; $i<10; $i++)
    <h2><b>{{ $i }}<b/>{{ $bar }}</h2>
@endfor

Works fine:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@php($foo = 'foo')
<h1>{{ $foo }}</h1>
@php($bar = $foo . 'bar');
@for($i = 1; $i<10; $i++)
    <h2><b>{{ $i }}<b/>{{ $bar }}</h2>
@endfor

Also works fine:

@php
    $foo = 'foo';
@endphp
<h1>{{ $foo }}</h1>
@php
    $bar = $foo . 'bar';
@endphp
@for($i = 1; $i<10; $i++)
    <h2><b>{{ $i }}<b/>{{ $bar }}</h2>
@endfor

An error

Example

>Solution :

It seems to be a scoping issue (or whatever you want to call it) as I mentioned in the comments.

I did some testing in my own project.
Adding below code snippet in a view;

@php($foo = 'foo')
<p>{{ $foo }}</p>
@php
    $bar = $foo . 'bar';
@endphp
@for($i = 1; $i<10; $i++)
    <h2><b>{{ $i }}<b/>{{ $foo }}</h2>
@endfor

Results in the below, raw PHP output:

<?php($foo = 'foo')
<p>{{ $foo }}</p>
@php
    $bar = $foo . 'bar';
?>
<?php for($i = 1; $i<10; $i++): ?>
    <h2><b><?php echo e($i); ?><b/><?php echo e($bar); ?></h2>
<?php endfor; ?>

You can see why it fails, the @php($foo = 'foo') directive is seen as a starting PHP tag which does not end until the @endphp directive after the $bar variable initialization. That means that all the code between the @php($foo = 'foo') and @endphp directives is not seen as PHP code.

Laravel also does not recommend the usage of the inline PHP directive anymore, as can be seen in this (quite recent) reply to someone with the same issue.

So, I recommend (as do they), to just use a regular PHP block as you did in your last example:

@php
    $foo = 'foo';
@endphp
<h1>{{ $foo }}</h1>
@php
    $bar = $foo . 'bar';
@endphp
@for($i = 1; $i<10; $i++)
    <h2><b>{{ $i }}<b/>{{ $bar }}</h2>
@endfor
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading