add laravel custom blade directive with variable scope

Viewed 28

I need to create a custom blade directive like @error like this:

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

what i want to do is to 2 vars like message that i can access within the directive scope only

i used, but both didn't work:

Blade::if('test', function($text){
    echo '<?php $v1 = "this is ok";?>';
    View::share('v2', "test2");

    return true;
});
1 Answers

Here is the steps if its works for you

Step 1 - Create the service provider

php artisan make:provider BladeServiceProvider

Step 2 - Define our directive The first thing it's to include the Blade facade, writing use Blade in the top of our code after the namespace declaration.

Step 3 - In boot() method create a new directive as below

namespace App\Providers;

use Blade;

use Illuminate\Support\ServiceProvider;

class BladeServiceProvider extends ServiceProvider {

  public function boot()
  {
     /**
      * Bootstrap any application services.
      *
      * @return string
      */

    // Add @var for Variable Assignment
    // Example: @var('foo', 'bar')

    Blade::directive('var', function ($expression) {
        // Strip Open and Close Parenthesis
        $expression = substr(substr($expression, 0, -1), 1);

        // Split variable and its value
        list($variable, $value) = explode('\',', $expression, 2);

        // Ensure variable has no spaces or apostrophes
        $variable = trim(str_replace('\'', '', $variable));

      // Make sure that the variable starts with $
      if (!starts_with($variable, '$')) {
          $variable = '$' . $variable;
      }

        $value = trim($value);

        return "<?php {$variable} = {$value}; ?>";
    });
  }

 /**
  * Register any application services.
  *
  * @return void
  */
 public function register()
 {
    //
 }
}

Now you can test this before testing

First, clear your views cache with the command php artisan view:clear and then create a blade file in your Laravel project with this content:

for example:-

@var('foo', 'bar')
Related