Laravel 5 firstOrCreate even retains unique settings for the field

Below is my application \ Cart.php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Cart extends Model {
    use SoftDeletes;
    protected $table = 'cart';
    protected $fillable = ['sess','uid'];
}

Below is my application \ Http \ Controllers \ CartController.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]);
    }

I want to check the database if the session key exists in the cart.sess table, otherwise create a new one and get the identifier.

The question is when it continues to create a new duplicate session in the database.

Cart table

Can I find out where I made a mistake?

thank

UPDATE [2015-05-27 16:02]: After the table, I TRUNCATE and set the sess field to Unique, first send it in order, and then send it the following error: After change to unique

UPDATE [2015-05-27 16:16] The code I use to create the database is:

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;
+4
source share
2 answers

, , sess , . , :

$table->unique('sess');

, .

, ,

sess varchar(40) NOT NULL

sess 255 , 40 . Laravel 64 ( ), :

8a9f119eaea027def7268d12e4e4d680

, . 40, sess 40 :

8a9f119eaea

, 8a9f119eaea027def7268d12e4e4d680, 8a9f119eaea.

+1

. SoftDeletes; , 0000-00-00 00:00:00, null .

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;

deleted_at timestamp

firstOrCreate ( ) enter image description here

: https://github.com/barryvdh/laravel-debugbar , .

0

All Articles