I'm developing a user management website using laravel 5.1.
Users are not allowed to register but they are able to see their profiles. Registration can be done only by the admin, so i have two types of users (Admin and normal users).
I'm following this tutorial: https://www.youtube.com/watch?v=8AQLUZ0X9ME everything was ok until I reached to the User Model
User table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->softDeletes();
$table->integer('role_id')->unsigned();
$table->timestamps();
});
Role table:
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('role_name');
//
});
}
Role Model:
class Role extends Model
{
protected $table = 'roles';
protected $fillable = ['role_name'];
public function users()
{
return $this->hasMany('App\User');
}
User model:
public function role(){
return $this->belongsTo('App\Role','role_id');
}
public function hasRole($title){
$user_role = $this->role();
if(!is_null($user_role)){
$user_role = $user_role->role_name; //here is the problem with role_name
}
return ($user_role===$title)?true:false;
}
In PHPStorm the role_name is highlighted in yellow and it says
Field 'role_name' not found in class \Illuminate\Database\Eloquent\Relations\BelongsTo less... (Ctrl+F1) Referenced field is not found in subject class. Note: Check is not performed on objects of type "stdClass" or derived.
I created 3 middlewares Update, Create, and Delete and they all have the same handle function:
public function handle($request, Closure $next, $Admin)
{
$User = $request->user();
return ($User->hasRole($Admin))?$next($request):response(view('errors.401'),401);
}
Routes file:
Route::get('/users','UserController@index');
Route::post('/users/create',['middleware'=>'create:Admin','uses'=>'UserController@store']);
Route::patch('/users/{id}',['middleware'=>'update:Admin','uses'=>'UserController@update']);
Route::delete('/users/{id}',['middleware'=>'delete:Admin','uses'=>'UserController@destroy']);
whenever i open up the create page i got this error:
"ErrorException in C:\wamp\www\laravelU\project - Copy5\app\User.php line 42: Undefined property: Illuminate\Database\Eloquent\Collection::$role_name"
I have been dealing with this code for 3 nights i need your help. if there is any easier way to achieve my goal without using packages ?