Afraz Ahmad
Afraz Ahmad

Reputation: 5416

Laravel 5.3 Update record. Only update changed record and leave the unchanged record

enter image description hereenter image description hereI want to update a profile and when I update the record, the old data that I didnot change is also updated.

I want to update only those values that are changed. Unchanged values should not be updated.

Route:

Route::post('/profile/settings/{user}', 'Admin\userController@UpdateProfileSettings')->name('profile.settings');

Controller Method:

 public function UpdateProfileSettings(Request $request, User $user)
{

    if (auth()->user()->id == $user->id) {

        $user->update([
            'name' => $request->name,
            'qualification' => $request->qualification,
            'institute' => $request->institute,
            'gender' => $request->gender,
            'speciality' => $request->speciality,
            'address' => $request->address,
        ]);

        return redirect()->back();
    } else {
        abort(403, "Unauthorized");
    }
}

Upvotes: 1

Views: 459

Answers (1)

Shady Atef
Shady Atef

Reputation: 2401

You can try the following

$name = $request->input('name', $user->name);

For laravel 5.4 : Also makesure that TrimStrings and ConvertEmptyStringsToNull middlewares in your application's global middleware stack found inside App\Http\Kernel

For laravel 5.3, you can manually add these middle-wares, to your project.. Adding TrimgStrings is illustrated here.

Adding ConvertEmptyStringsToNull will follow the same steps..

Create a new file ConvertEmptyStringsToNull.php

<?php
namespace App\Http\Middleware;
class ConvertEmptyStringsToNull extends TransformsRequest
{
    /**
     * Transform the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function transform($key, $value)
    {
        return is_string($value) && $value === '' ? null : $value;
    }
}
  1. Register the middleware as global by adding into your App\Http\Kernel.php

    protected $middleware = [
    \Illuminate\Foundation\Http\Middlewar\CheckForMaintenanceMode::class,
    \App\Http\Middleware\TransformsRequest::class,
    \App\Http\Middleware\TrimStrings::class,
    \App\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];
    

Upvotes: 2

Related Questions