3

I have a problem with firstOrNew() method of the Laravel eloquent class. the problem is that when I give the method some attributes and values and call save() on the model, it doesn't get saved (inserted or updated).

PHP :

<?

$flightModel = Flight::firstOrNew([
    'arrival' => $flightData['arrival'],
    'plane' => $flightData['plane']
]);

$flightModel->departure = $flightData['departure'];

$flightModel->save();//this doesn't save any data

But when I try this with a new model it gets saved :

<?

$flightModel = new Flight();
$flightModel->arrival = $flightData['arrival'];
$flightModel->plane = $flightData['plane'];
$flightModel->departure = $flightData['departure'];

$flightModel->save();

Thanks for helping.

Ramin Omrani
  • 3,673
  • 8
  • 34
  • 60
  • 1
    Is `arrival` and `plane` set to fillable in your Flight model? – aynber Jul 05 '16 at 16:15
  • @aynber I have set `$fillable` to `'*'` and `$guarded` to `[]` – Ramin Omrani Jul 05 '16 at 16:16
  • 1
    Can you use a wildcard? I didn't think that was an option. Perhaps try explicitly setting `arrival` and `plane`, because what you have above should work. Also, you should specify _either_ `fillable` or `guarded`, as per the [docs](https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models). – camelCase Jul 05 '16 at 16:23
  • Looking at the Model.php, only guarded can use a wildcard. You must explicitly set each fillable field. – aynber Jul 05 '16 at 16:33
  • @camelCase I have set the fields explicitly on the `$fillable` variable but no luck. nothing changed – Ramin Omrani Jul 05 '16 at 16:40
  • @aynber I have set the fields explicitly on the `$fillable` variable but no luck. nothing changed – Ramin Omrani Jul 05 '16 at 16:41
  • Also I have used on of those 2 properties : `fillable` or `guarded` – Ramin Omrani Jul 05 '16 at 16:41
  • How about trying `firstOrCreate` instead, does it create the new model? – camelCase Jul 05 '16 at 16:52

0 Answers0