validate if a record exists before inserting laravel 5.5

1

I am trying to make an insert in a table with a many-to-many relationship. My doubt is if there is any way to validate, if that relationship exists do not add it again this is the code that I use but I do not know if eloquent already brings something similar.

    // Conseguimos el objeto
$peli=Pelicula::where('fk_segmento', "1")
->where('fk_empresa', '1')
->first();

// Si existe
if(count($peli)>=1){
   //realizo el insert
}  
    
asked by Andersson Meza Andrade 18.10.2017 в 23:35
source

2 answers

1

The other answer gives a good idea, but it is not entirely correct and that is why the syntax that works is the one you put in the comment and not the response as such.

Below the explanation:

This is the code for the firstOrCreate() method, located at link

/**
 * Get the first record matching the attributes or create it.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model
 */
public function firstOrCreate(array $attributes, array $values = [])
{
    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }

    return tap($this->newModelInstance($attributes + $values), function ($instance) {
        $instance->save();
    });
}

As explained by the documentation and as seen in the code, the first array of parameters are the attributes with which the search will be performed in the database, and the second array are the additional values with which the model will be created / record in the database, in case no record is found that matches the attributes of the first array.

In that order of ideas,

Pelicula::firstOrCreate(['fk_segmento' => '1'], ['fk_empresa' => '1']);' 

DOES NOT WORK because you are telling Eloquent to look for a record that has fk_segmento = 1 , and if you can not find it, create it together with the value fk_empresa = 1 .

The code you put in the comment:

Pelicula::firstOrCreate(['fk_segmento' => '1', 'fk_empresa' => '1']);

tells Eloquent to look for a record that has the values fk_segmento = 1 and fk_empresa = 1 (and that you create it if you can not find it), which is consistent with what you propose in the code of the question:

...
where('fk_segmento', "1")
->where('fk_empresa', '1')
    
answered by 19.10.2017 / 07:09
source
0

For that you could use the firstOrCreate , this method what it does is look for a record in the database according to the parameters that you pass, if you do not find any record then create it

Pelicula::firstOrCreate(['fk_segmento' => '1'], ['fk_empresa' => '1']);
    
answered by 18.10.2017 в 23:40