laravel 5.2 - 检查字段是否为空

时间:2016-05-06 17:37:33

标签: laravel passwords field

我想检查一些字段是否为空。如果为空,则用户可以在不更改当前密码的情况下更新配置文件。 如果不为空,则存储密码的新值。我的控制器是:

public function storeUpdatedUser(Request $request)
{
    $this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);

    $user = User::findOrFail(Auth::user()->id);
    $user->update($request->all());
    $new_password = false;

    if($new_password != ""){
        $new_password = bcrypt($request->new_password);
        $user->password = $new_password;
    }

    $user->save();
    Session::flash('flash_message', 'User updated!');

    return redirect('/');           
}

但是没有用,如果我放了一些值就没有密码更改 图像说明更好 enter image description here

3 个答案:

答案 0 :(得分:4)

试试这个:

public function storeUpdatedUser(Request $request)
{
    $this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);

    $user = User::findOrFail(Auth::user()->id);
    $user->update($request->all());

    if(!empty($request->input('new_password'))) {
        $new_password = bcrypt($request->input('new_password'));
        $user->password = $new_password;
        $user->save();
    }

    Session::flash('flash_message', 'User updated!');

    return redirect('/');           
}

答案 1 :(得分:0)

这是在Laravel 5.7中对我有用的东西:

$user = Auth::user();    
$user->update($request->filled('password') ? $request->all() : $request->except(['password']));

答案 2 :(得分:0)

Laravel 检查请求输入是否存在

if($request->has('new_password ')) {
    dd('new_password is exists.');
} else {
    dd('new_password is not exists.');
}

Laravel 检查请求输入字段是否为空

if($request->filled('new_password ')) {
    dd('new_password is not empty.');
} else {
    dd('new_password is empty.');
}

Laravel 检查请求输入字段是否为空

if(!empty($request->input('new_password '))) {
    dd('new_password is not empty.');
} else {
    dd('new_password is empty.');
}