![]() User's existence will be only checked via email, but when created, the new record will save both email and name. Which means you can use it like this: User::firstOrCreate(, ) In Laravel 5.3, the firstOrCreate method has the following declaration: public function firstOrCreate(array $attributes, array $values = ) The Eloquent allmethod will return all of the results in the model's table. The firstOrCreate is available in Laravel 5x, the answer is too old and it was given for Laravel-4.0 in 2013. ![]() Instead of creating a static method, you can use a scope in the Model, so the method in the Model will be scopeMethodName and call Model::methodName(), same as you did in the static method, for example $user = User::findOrCreate(5) Warning : This retrieves every single article from the database and loads them all into memory, and then selects just one from all that data and returns it. This is another way to do the same thing: public function scopeFindOrCreate($query, $id) Eloquent method find() may accept multiple parameters, and then it returns a Collection of all records found, not just one Model. You need to get the articles first before you can call find() I believe. If a user with id of 5 exists, then it'll be updated, otherwise a new user will be created but the id will be last_user_id + 1 (auto incremented). There is already a method findOrFail available in Laravel and when this method is used it throws ModelNotFoundException on fail but in your case you can do it by creating a method in your model, for example, if you have a User model then you just put this function in the model // Put this in any model and useįrom your controller, you can use $user = User::findOrCreate(5)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |