Ad

Users And Roles Tables Relationship Through Middleware Parameter Laravel 5.1

- 1 answer

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','[email protected]');
Route::post('/users/create',['middleware'=>'create:Admin','uses'=>'[email protected]']);
Route::patch('/users/{id}',['middleware'=>'update:Admin','uses'=>'[email protected]']);
Route::delete('/users/{id}',['middleware'=>'delete:Admin','uses'=>'[email protected]']);

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 ?

Ad

Answer

The reason you are getting an error when trying $user_role->role_name is because you're technically looking for the property role_name in the BelongsTo class.

When trying to access a relationship of an eloquent model you can either use it as a dynamic property i.e.

$user_role = $this->role;

or

$user_role = $this->role()->get();

So you can change your hasRole method to something like:

public function hasRole($title){

    if(is_null($this->role)){
        return false;
    }

    return $this->role->role_name === $title;
}

The reason your application is throwing a MethodNotAllowedHttpException is because you are trying to access a POST route with a GET request. (anytime you navigate to a page using a web browser it will be a GET request).

What you should do is change the Route::post('create' ... to Route::get('create'... ad add something like Route::post('store' to submit to.

Have a look at https://laravel.com/docs/5.1/controllers#restful-resource-controllers

Secondly, you don't need to have 3 different middleware classes if they are just checking if the user is an admin.

Lastly, have a look at https://laravel.com/docs/5.1/validation#form-request-validation (including the Authorizing section)

Hope this helps!

Ad
source: stackoverflow.com
Ad