1

I want to Update this data in database.

error :

ErrorException
Creating default object from empty value

i get error in this line :

$user->name = $request->name;

My Controller code is :

public function update(Request $request, $id)
{
    $this->validate($request, [
        'name' => 'required|max:255',
        'mobile' => 'required|numeric|regex:/(0)[0-9]/|not_regex:/[a-z]/|digits:11',
        'national_code' => 'required|numeric|regex:/(0)[0-9]/|not_regex:/[a-z]/|digits:10',
        'avatar' => 'required|mimes:jpg,jpeg,png',
    ]);

    $id = (int)$id;
    $user = User::findOrFail($id);
    $user->name = $request->name;
    $user->mobile = $request->mobile;
    $user->national_code = $request->national_code;
    $user->province = $request->province;
    $user->city = $request->city;
    $user->address = $request->address;
    $user->postcode = $request->postcode;
    $user->active = $request->active;
    $user->avatar = $request->avatar;


    if(! is_null($request->password)) {
        $request->validate([
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $user->password = $request->password;
    }

    $user->active = $request->active ? 1 : 0;

    if ($request->role_id) {
        $user->syncRoles($request->role_id);
    }
    $user->save();

    $notification = array(
        'message' => 'Success !',
        'alert-type' => 'success'
    );

    return redirect(route('management.users.index'))->with($notification);
}

Route :

Route::resource('users', 'UserController');

Thank you

9
  • 1
    could you add this error ? Commented Mar 31, 2020 at 6:31
  • @Joseph i added. Commented Mar 31, 2020 at 6:38
  • could you add your route to this method? Commented Mar 31, 2020 at 6:39
  • I don't think Route has anything to do with this error !! But i added. Commented Mar 31, 2020 at 6:44
  • first update your function header to this public function update(Request $request, User $user) and you could use it directly without useing findorfail Commented Mar 31, 2020 at 6:47

1 Answer 1

3

Try this:

$user = User::find($id)

or this:

$user = User::where('id', $id)->first();

And check if in your User Model:

protected $fillable = [
    'name','mobile', 'national_code', 'city', 'province', 'address', 
     'postcode', 'active', 'avatar',
];
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, User::find($id) worked, but User::findOrFail($id); have problem ?
laravel.com/docs/5.7/eloquent in documentation you can show why not work, findOrFail is for Exception capture

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.