Laravel中的异常处理

Eloquent try/catch on duplicate key Exception and delete?

I've a form for a new vendor where the controller listens for its POST.
From there on I'm creating a new endor and the equivalential login for this vendor.

Controller :

$vendor = Vendor::create( $request->all() );  
$login = Vendor::createLogin($vendor->vendor_id);

the createLogin function :

public static function createLogin($lid){  
    $name = self::find($lid)->vendor_name;  
    $name = explode(' ', $name);  
        
    $vendor_login = [
        'username' => strtolower( end($name) ) . '.vendor',
        'group' => 'vendor'
    ];
    
    try{
        $user = User::create( $vendor_login );
        return $user;
    }
    catch (Illuminate\Database\QueryException $e){
        $error_code = $e->errorInfo[1];
        if($error_code == 1062){
            self::delete($lid);
            return 'houston, we have a duplicate entry problem';
        }
    }

Creating a new, nonexistant one : works perfectly.
However the try/catch block never seems to be reached since
I'm always getting laravels inbuild error site with the QueryException
for the duplicate entry on the users table. How can I make it work,
that on a duplicate entry it deletes the vendor it set before from the
table Vendor AND returns an error to display for the user?

转自:https://laracasts.com/discuss/channels/eloquent/eloquent-trycatch-on-duplicate-key-exception-and-delete

Laravel框架数据库CURD操作、连贯操作使用方法

Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。

一、Selects

检索表中的所有行

$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}

从表检索单个行

$user = DB::table('users')->where('name', 'John')->first();
var_dump($user->name);

检索单个列的行

$name = DB::table('users')->where('name', 'John')->pluck('name');

检索一个列值列表

$roles = DB::table('roles')->lists('title');

该方法将返回一个数组标题的作用。你也可以指定一个自定义的键列返回的数组

$roles = DB::table('roles')->lists('title', 'name');

 

指定一个Select子句

$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();

Select子句添加到一个现有的查询

$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

where

$users = DB::table('users')->where('votes', '>', 100)->get();

Continue reading