user9277271
user9277271

Reputation:

Laravel 8 Does Not Update Information From Database

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.

Upvotes: 1

Views: 2628

Answers (2)

porloscerros Ψ
porloscerros Ψ

Reputation: 5078

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

Upvotes: 1

Donald Kagunila
Donald Kagunila

Reputation: 349

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();

Upvotes: 1

Related Questions