Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jim1506's avatar

Getting a Attempt to assign property 'admin' of non-object when adding to Users

I have amended the users table to add an integer field admin. I have a form which includes a checkbox for this:

              <div class="form-group col-xs-12">
                  <div class="checkbox ">
                      <input type="checkbox" name="admin" id="checkbox_372773_0" value="1" data-alias="" checked=""><label for="checkbox_372773_0" class="checkbox-inline">
                      &nbsp;&nbsp;admin </label>
                  </div>

                  <span id="checkbox_372773"></span>
              </div>

and in my controller I have a store method:

public function store(Request $request)
    {
         
         $us = new User;

         $us->name = $request->name;
         $us->email = $request->email;
         $us = Hash::make($request->password);

         if (isset($request->admin))
           { $us->admin = 1;}
         else
           {$us->admin = 0;}

         $us->save();
         session()->flash('success','the user has been added');
         return redirect()->route('users');
    }

if I run this I get the error

Attempt to assign property 'admin' of non-object

so I added

dd($request')

to check the incoming request

request: ParameterBag {#44 ▼
    #parameters: array:6 [▼
      "_token" => "TNaQs6HAwGUbz87PNRJoOeZcurIJgKbKnbEaAbWX"
      "name" => "Jim"
      "email" => "[email protected]"
      "password" => "aPassword"
      "admin" => "1"
      "button_569082" => null
    ]
  }

I have added the field to the fillable on the User.php:

protected $fillable = [
        'name', 'email', 'password','admin',
    ];

but it has made no difference, and of course I have not got to the store part of the controller method.

0 likes
6 replies
Nakov's avatar
Nakov
Best Answer
Level 73

maybe this line

$us = Hash::make($request->password);

should be this

$us->password = Hash::make($request->password);

And this

if (isset($request->admin))
           { $us->admin = 1;}
         else
           {$us->admin = 0;}

Can be replaced with ternary

 $us->admin = isset($request->admin) ? 1 : 0;
jim1506's avatar

Thanks Nakov. That was incredibly thick of me (it is 6.35 am here) and of course my attention was on the error and not the error on the line above.

All sorted thanks.

munazzil's avatar

Condition look like below,

    if ($request->admin == 1)

but you can access user using,

   auth()->user();

only

Snapey's avatar

It really annoys me that @munazzil is getting XP for each of his stupid answers

2 likes

Please or to participate in this conversation.