Z
Z
Zhenya Starikov2021-04-12 11:00:18
Laravel
Zhenya Starikov, 2021-04-12 11:00:18

Why is the blade directive not registered?

I'm trying to make a blade directive that would check the user's role (whether he is an administrator). All tables, links, models seem to be there.
In order not to write long constructions in the view type (they work)

@if(auth()->check() && auth()->user()->hasRole('admin')):

decided to make the role directive.

Created a RoleServiceProvider with the following content:
class RoleServiceProvider extends ServiceProvider
{
    public function boot() {
        /*Blade::directive('role', function ($role) {
            return "<?php if(auth()->check() && auth()->user()->hasRole({$role})): ?>";
        });
        Blade::directive('endrole', function ($role) {
            return "<?php endif; ?>";
        });*/

        Blade::if('role', function ($role) {
            return auth()->check() && auth()->user()->hasRole({$role});
        });
    }
}

Registered it in config/app.php:
'providers' => [
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

        //добавляем новые service providers
        App\Providers\RoleServiceProvider::class,

However, in such a simple construction
@extends('layouts.layout')
@section('title', 'Каталог')
@section('content')
  <main id="content">
      <div class="container">
        <div class="row">
          @role('admin')
            <p> admin </p>
          @else
            <p> not admin </p>
          @endrole
        </div>
      </div>
  </main>
@endsection

throws an error on the @else line
ParseError
syntax error, unexpected 'else' (T_ELSE), expecting end of file (View: D:\labs\laravelSSPR\resources\views\catalog.blade.php)

If I remove else, it turns out that he simply skips these directives and prints to me on the screen
@role('admin')
  <p> admin </p>
@endrole

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zhenya Starikov, 2021-04-14
@evster-coder

The thing was, the configuration settings were cached, it was necessary to clean them throughphp artisan config:clear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question