Laravel 5.5 controller update function issue

I have the update function in the controller where I want to store the values of a form. Here is the code;

public function update(Request $request, $id=1){
        $data = array(); 

        $data->firstName = $request->get('firstName');
        $data->lastName  = $request->get('lastName');
        $data->email     = $request->get('email');
        $data->company   = $request->get('company');
        $data->website   = $request->get('website');
        UserAdmin::where('id', Auth::user()->id)->update($data);

        //return view('Administrator.profile.profile',$data);
        return redirect('administrator/myprofile');
    }

However, after submitting the form, it show me the error;

Attempt to assign property of non-object

Upvotes: 0

Views: 250

Answers (2)

Kyle Wardle
Kyle Wardle

Reputation: 830

You are trying to use an object operator (->) on an array.

For what you are trying to achieve it would be best to use the model to your advantage. By using findOrFail() you can return an object.

public function update(Request $request, $id=1){

    $data = UserAdmin::findOrFail(Auth::id());
    $data->firstName = $request->get('firstName');
    $data->lastName  = $request->get('lastName');
    $data->email     = $request->get('email');
    $data->company   = $request->get('company');
    $data->website   = $request->get('website');
    $data->save();

    //return view('Administrator.profile.profile',$data);
    return redirect('administrator/myprofile');
}

This would achieve what you want but is cleaner. Look at the Laravel Eloquent Documentation here.

Upvotes: 1

Loek
Loek

Reputation: 4135

That's because you can't assign array values with $data->key. An array is not an object and as such has a different syntax.

This wil work however:

public function update(Request $request, $id=1){
    $data = array(); 

    $data['firstName'] = $request->get('firstName');
    $data['lastName'] = $request->get('lastName');

    // etc
}

Upvotes: 3

Related Questions