mysqllaravel-5laravel-query-builderilluminate-container

How to insert if not exist illuminate slim framework


I use slim framework and use illuminate/database.

I would like to insert data which not duplicate function_number but if different product_id function_number can be duplicate, for example

enter image description here

here is my mode

$app->post('/create_function', function($request, $reponse, $args) {
   $query = $this->db->table('functions')->insert([
            'project_id' => $request->getParam('project_id'),
            'function_number' => $request->getParam('function_number'), 
            'function_text' => $request->getParam('function_text'),
            'created' => date('Y-m-d')
         ]);
   if($query) {
     echo "Function was created";
   }
});

Solution

  • According to your request you want that the couple (project_id, function_number) be unique. To do so, you need to query your DB as follows:

    //Check for duplicate  
    $exists = $this->db->table('functions')->where('project_id', '=', $request->getParam('project_id'))->where('function_numbe', '=', $request->getParam('function_number'))->exists();
    
    if(!$exists) {
        //Your insert code here 
    }