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?
Best How To :
You're using the wrong method. You're looking for the
firstOrNew() method, not
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.
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.