1

I want to update my user information from database. I have this as form:

<form method="POST" action="{{ route('profile.update' , ['profile' => Auth::user()->id]) }}" class="form">
    <div class="form-group BSinaBold ">
        <input id="location" type="text" class="form-control" name="location" value="{{ Auth::user()->location }}" required autocomplete="location" autofocus>
    </div> 
</form>

And at the Controller, I put this in the method update:

public function update(Request $request, $profile)
    {
        $validate_data = Validator::make(request()->all(),[
           'location' => 'required'
        ])->validated();

        $user = User::findOrFail($profile);

        $user->update([
            'location' => $validate_data['location']
        ]);

        return back();
    }

But now the problem is, it does not update location. I mean there is no error appearing and no update at all!

So what's going wrong here, how can I fix this?

I would really appreciate any idea or suggestion from you guys,

Thanks.

3
  • 4
    Have you looked at your User model's fallible fields? You cannot use update() will ignore fields not on that list. Commented Feb 23, 2021 at 15:51
  • What have you tried to debug the problem? Commented Feb 23, 2021 at 15:55
  • 1
    Just to mention I think there is a typo in @NMahurin comment, they mean fillable and it is a measure against "Mass assignment" laravel.com/docs/8.x/eloquent#mass-assignment Commented Feb 23, 2021 at 16:23

2 Answers 2

1

From the code provided, you are updating data from $validate_data, update your code to use the request data

$user = User::find($profile);

$user->location = request('location');

$user->save();
Sign up to request clarification or add additional context in comments.

Comments

1

Instead manually creating the validator, you could use the validate method provided by the Illuminate\Http\Request object:

$validated = $request->validate([ 'location' => 'required' ]);

Reference


Then you can mass update the record (note you doesn't need to retrive the record to update it, just update it):

User::where('id', $profile)
      ->update($validated);
  

Reference


However, before using the update method, you will need to specify either a fillable or guarded property on your model class.

class User extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        // other fields here...,
        'location',
    ];
}

Reference

Comments

Your Answer

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