Итак, я добавил столбец к Users table
для роли пользователя, которая role
;
Пользователь может иметь только одну роль, роль возвращается null
Role.php (модель)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'role'
];
public function users() {
return $this->hasMany('App\User');
}
}
User.php (модель)
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'role', 'first_login', 'last_login', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role() {
return $this->belongsTo('App\Role');
}
}
UserController.php (только индекс)
public function index()
{
$users = User::with('role')->get();
return view('users.index')->with('users', $users);
}
index.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>USERS</h1>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{$user->first_name}} {{$user->last_name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->role}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
@endsection
Роль пользователя: null .
Как правильно это сделать?
структура таблицы
+-------+
| Users |
+-------+
| id |
| role | -> id of role
| ... |
+-------+
+-------+
| Roles |
+-------+
| id |
| role | -> name of role
| ... |
+-------+