Как получить правильные значения из БД в Laravel 5.8 - PullRequest
0 голосов
/ 26 мая 2019

Я начинающий в Ларавеле.У меня есть этот код:

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];


    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }


    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }
        return false;
    }

}

class Role extends Model
{
    protected $quarded = [];
    public $timestamps = false;

    public function users()
    {
        return $this->belongsToMany('App\User');
    }

}

и схема:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });


Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });



Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

И мой пользователь:

DB::table('users')->insert([
            'name' => 'Marian',
            'surname' => 'La',
            'email' => 'marian@icloud.com',
            'email_verified_at' => \Carbon\Carbon::now(),
            'password' => Hash::make('passw'),
        ]);       

DB::table('role_user')->insert([
                'user_id' => 1,
                'role_id' => 1,
            ]);

Этот код работает нормально.У меня проблема с моей ролью.Как я могу напечатать роль пользователя в блейде?

Я делаю этот код:

public function getAdmin(int $id)
    {
        return User::find($id);
    }

$admin = $this->getAdmin(1);

И теперь у моего $ admin - есть объект администратора.

Когда я печатаю в блейдеfile: $ admin-> name, $ admin-> фамилия - это работа.

Когда я печатаю: {{$ admin-> role}} *

У меня есть результат:

[{"id":1,"name":"admin","pivot":{"user_id":1,"role_id":1}}]

Как я могу показать правильное значение (admin):

Мне нужен результат: admin не это: [{"id": 1, "name": "admin", "pivot": {" user_id ": 1," role_id ": 1}}]

1 Ответ

1 голос
/ 26 мая 2019

То есть Отношение ко многим , и у каждого пользователя может быть много ролей!Поэтому используйте foreach, чтобы напечатать все правила на вашем блейде :

@foreach ($admin->roles as $role)
  {{ $role -> name }},
@endforeach

https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...