PHP code inside a Laravel 5 blade template

120,694

Solution 1

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.

Solution 2

Just open and close PHP tags:

<?php $style = '...'; ?>

Solution 3

In modern Laravel (6/7) you should do this:

@php
   yourphpcode();
@endphp

Solution 4

Laravel recipes suggest a simple, but effective, way to do it without including the PHP tags:

{{--*/ $var = 'test' /*--}}

{{-- --}} works as a blade comment / and / reverts the effect of comment resulting on

<?php $var = 'test' ?>

The problem is that is longer than including PHP tags :-(

Solution 5

The following new NewBladeCompiler will use @{ }} for accepting all PHP code like variable assigning, class declaration, etc.

E.g. @{ $variable = 0; }} will be compiled to <?php $variable=0; ?>

<?php

    use Illuminate\View\Compilers\BladeCompiler;

    class NewBladeCompiler extends BladeCompiler
    {

        /**
         * Get the echo methods in the proper order for compilation.
         *
         * @return array
         */
        function getEchoMethods()
        {
            $methods = [
                'compileRawEchos'     => strlen(stripcslashes($this->rawTags[0])),
                'compileEscapedEchos' => strlen(stripcslashes($this->escapedTags[0])),
                'compileRegularEchos' => strlen(stripcslashes($this->contentTags[0])),
                'compilePhpEchos'     => strlen(stripcslashes("@{"))
            ];

            uksort($methods, function ($method1, $method2) use ($methods) {

                // Ensure the longest tags are processed first
                if($methods[$method1] > $methods[$method2])
                {
                    return -1;
                }
                if($methods[$method1] < $methods[$method2])
                {
                    return 1;
                }

                // Otherwise give preference to raw tags (assuming they've overridden)
                if($method1 === 'compilePhpEchos')
                {
                    return -1;
                }
                if($method2 === 'compilePhpEchos')
                {
                    return 1;
                }
                if($method1 === 'compileRawEchos')
                {
                    return -1;
                }
                if($method2 === 'compileRawEchos')
                {
                    return 1;
                }
                if($method1 === 'compileEscapedEchos')
                {
                    return -1;
                }
                if($method2 === 'compileEscapedEchos')
                {
                    return 1;
                }
            });

            return $methods;
        }

        function compilePhpEchos( $value )
        {
            $pattern  = sprintf('/(@)?%s\s*(.+?)\s*%s(\r?\n)?/s', "@{", "}}");
            $callback = function ($matches) {
                $whitespace = empty($matches[3]) ? '' : $matches[3] . $matches[3];
                return $matches[1] ? substr($matches[0], 1) : '<?php ' . $matches[2] . ' ?>' . $whitespace;
            };
            return preg_replace_callback($pattern, $callback, $value);
        }

    }

?>
Share:
120,694

Related videos on Youtube

abu abu
Author by

abu abu

Updated on September 13, 2020

Comments

  • abu abu
    abu abu over 3 years

    I have to place some PHP code inside a Laravel 5 blade template. Like below

    @foreach ($farmer->tasks as $task)
        @if ($task->pivot->due_at) < date(now))
            $style = 'alert alert-danger';
        @elseif ($task->pivot->due_at) > date(now))
            $style = 'alert alert-success';
        @else
            $style = '';
        @endif
    @endforeach
    

    What is the actual procedure to place PHP code inside a Laravel 5 blade template?

  • Aleksandar Belic
    Aleksandar Belic almost 5 years
    Seems like the only solution for Laravel 4, since @php directive is not supported.
  • Slavic
    Slavic over 3 years
    I have just lost 1 hour wondering how a variable got its value, when it was commented out.. Thank you.
  • Tanckom
    Tanckom over 3 years
    Actually curious about the differences between @php and <?php ... I mean there was probably a reason to add these directives.
  • I. Antonov
    I. Antonov over 2 years
    @Tanckom As far as I understand they are no differences between writing @php and <?php. I have worked with people who prefer to write <?php over @php, and their main reason behind it was that they are more comfortable with it as they have been using it for a while in Raw PHP. But often during code reviews I usually end up changing them back to @php as this is the way I prefer to write it. In Laravel's documentation is it asked to write @php. I guess it is because to maintain the consistency of the Blade syntax.
  • Peilonrayz
    Peilonrayz over 2 years
    @I.Antonov Using one of @php or <?php should be defined in your company's style guide. Flip-flopping between styles based on who touched the file last is not what code reviews are meant to do.
  • I. Antonov
    I. Antonov over 2 years
    @Peilonrayz Yeah, I tried to get them to do that. But initially they weren't interested as they "didn't have time for it". Instead we were assigned to changing it during reviews and push the finals. Just sharing a scenario. And I don't work there anymore.