-1

i want to change the role of a user and from one role to another role but I am getting an error that says:

Trying to get property 'Role_name' of non-object

Trying to get property 'Role_name' of non-object

this is my update function in the controller public function update(Request $request,User $user ) {

    $role=Role::where('Role_name',$request->rolename)->first();
    if($role->Role_name!=='Normal user' && $user->is_admin=1){
        $user->roles()->sync($role);
    }
    elseif($role->Role_name!=='Normal user' && $user->is_admin=1){
        $user->roles()->sync($role);
        $user->update(['is_admin'=>0]);
    }
    return redirect( url('admin/admins') )->with('success','Ucwords($user->name) has been Updated Successfully');
    
}

update function

and also this is the blade view

bladeview

I have not understood where the problem is because it's returning an error. this is my roles table

roles table

my users table

users table

How I can solve this?

  • 1
    Please don't post pictures of your code. If someone would like to help you and copy your code... he/she can't do that from a picture. – James Z Jun 04 '21 at 09:42

2 Answers2

0

To make sure $role is always set, you can use firstOrFail();

$role = Role::where('Role_name',$request->rolename)->firstOrFail();

Probably the variable is not set, this will make sure that it is not null;

Bono495
  • 43
  • 11
  • its returns an error of 404 not found even when i dd($role) – stephen waweru99 Jun 04 '21 at 10:05
  • 1
    this is how i was able to debug i changed the 'Role_name' to 'id'. from $role=Role::where('Role_name',$request->rolename)->first(); to $role=Role::where('id',$request->rolename)->first(); as I have set the value as an id – stephen waweru99 Jun 07 '21 at 05:25
0

in your select tag roles, your value is id so in controller it should be like this.

$role = Role::findOrFail($request->rolename);
Jimbo Magusib
  • 191
  • 2
  • 3