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')