Laravel 在 save() 上缓和错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22272368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:09:02  来源:igfitidea点击:

Laravel moderate errors on save()

phplaravellaravel-4

提问by DolDurma

In this sample code below how would I moderate errors such as Eloquent could not save or update fields or break SQL connection?

在下面的示例代码中,我将如何缓和诸如 Eloquent 无法保存或更新字段或中断 SQL 连接之类的错误?

$user = new User;

$user->name = 'John';

$user->save();

回答by Steve Bauman

The save() method for eloquent returns a boolean on failure and a collection object on success, so you can display an error if the save() method returns false;

eloquent 的 save() 方法在失败时返回一个布尔值,在成功时返回一个集合对象,因此如果 save() 方法返回 false,您可以显示错误;

For example:

例如:

$user = new User;

$user->name = 'John';

if($user->save()){
    return Redirect::to('users')->with('message', sprintf('User: "%s" successfully saved', $user->name));
} else{
    return Redirect::to('users')->with('message', 'Failed to create user');
}

Here's the eloquent save function in detail:

下面详细介绍一下 eloquent save 功能:

http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_save

http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_save

You may also want to look at model events:

您可能还想查看模型事件:

http://laravel.com/docs/5.1/eloquent#events

http://laravel.com/docs/5.1/eloquent#events

EDIT: For your other question to catch a database connection error you can use a try/catch block such as:

编辑:对于捕获数据库连接错误的其他问题,您可以使用 try/catch 块,例如:

try{
    if (Auth::attempt(array('email' => $email, 'password' => $password))){
        return Redirect::to('dashboard');
    } else{
        //Authentication failed
        return Redirect::to('home')->with('message', 'Authentication failed, username/password inccorrect');
    }
} catch(PDOException $e){
    return Redirect::to('home')->with('message', sprintf('Failed to connect to database: %s', $e));
}