Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laraver FindOrNew with multiple parameters

I'm using laravel FindOrNew() to get an entry with two parameters, or create a new one:

$option = \App\Option::findOrNew(['user_id' => $this->id , 'option_name' => $optionName]);

I want to get an option for a user that has the name in $optionName. The problem is that it just checks for the user_id, and does not create a new one when option_name does not exist.. instead it "finds" one which does not match the $optionName value..

Can someone say what I'm doing wrong? How can I achieve this?

like image 710
sigmaxf Avatar asked Jun 19 '15 04:06

sigmaxf


Video Answer


1 Answers

TL;DR:

You're using the wrong method. You're looking for the firstOrNew() method, not findOrNew().

Explanation:

The findOrNew() is an extension of the find() method, which works on ids only. It takes two parameters, the first being the id (or array of ids) to find, and the second being the columns to retrieve. It's treating the array you've passed in as an array of ids to find.

The firstOrNew() method takes one parameter: an array of attributes to search for. It will turn the array into a where clause, and then call first() on the query builder. If no results are returned, it returns a new instance with those attributes filled in.

like image 102
patricus Avatar answered Sep 22 '22 02:09

patricus