Laravel 5.3更新记录。仅更新已更改的记录并保留未更改的记录

时间:2017-03-10 13:07:54

标签: php http sql-update laravel-5.3

enter image description here enter image description here我想更新个人资料,当我更新记录时,我未更改的旧数据也会更新。

我想只更新那些已更改的值。不应更新未更改的值。

路线:

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

控制器方法:

 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");
    }
}

1 个答案:

答案 0 :(得分:2)

您可以尝试以下

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

对于laravel 5.4: 还可以确保在TrimStrings

中找到应用程序的全局中间件堆栈中的ConvertEmptyStringsToNullApp\Http\Kernel个中间件

对于laravel 5.3,您可以手动将这些中间件添加到项目中。 说明了添加TrimgStrings here

添加ConvertEmptyStringsToNull将遵循相同的步骤..

创建新文件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. 通过添加到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,
    ];