Laravel 5 firstOrCreate keep create even set unique to the field

Below is my appCart.php

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
class Cart extends Model {
    use SoftDeletes;
    protected $table = 'cart';
    protected $fillable = ['sess','uid'];
}

Below is my appHttpControllersCartController.php

public function cart($id=0, $act, Request $request)
    {
        $sessId = Session::getId();
        switch($act){
            case 'Add':
                $quantity = $request->only('p_quantity');
                $data = $request->except('p_quantity');
                $cartId =  Cart::firstOrCreate(['sess' => $sessId,'status' => 1]);
            break;

            case 'Delete':

            break;
        }

        return response()->json(['success' => true,'message' => 'Success', 'act' => $act, 'id' => $id ,'data' => $data, 'quantity'=> $quantity, 'cart'=>$cartId->id]);
    }

What i want is check database if the session key exist in table cart.sess, else create new one and get the id.

Question is , when it keep create new duplicate session to database.

Cart Table

may i know where i did wrong?

Thanks

UPDATE [2015-05-27 16:02]:
After i TRUNCATE table and set the sess field to Unique , first submit it look ok, when second submit it show error below:
After change to unique

UPDATE [2015-05-27 16:16]
Code that i use to create database:

CREATE TABLE IF NOT EXISTS `cart` (
  `id` int(11) NOT NULL,
  `uid` int(11) DEFAULT NULL,
  `sess` varchar(40) NOT NULL,
  `status` int(11) DEFAULT '1',
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


Source: laravel

Leave a Reply