firstOrNew, firstOrCreate, firstOr and updateOrCreate methods in laravel
The following is developed by LaravelThe introductory tutorial column will introduce you to the firstOrNew, firstOrCreate, firstOr and updateOrCreate methods in laravel. I hope it will be helpful to friends in need!
If you have ever used Laravel, you probably know the standard ways to create Eloquent models, such as make(), create(), update, and save(). Laravel also provides some other methods that people don't realize are also very useful for creating and updating models. Therefore, in this article I would like to introduce some other methods and show that they may be useful:
firstOrNew
firstOrNew method finds the first one that satisfies certain constraints Model, new creates a new model when there is no data that satisfies the constraints.
You can use the following code:
$user = User::where('email', request('email'))->first(); if ($user === null) { $user = new User(['email' => request('email')]); } $user->name = request('name'); $user->save()
and rewrite it as:
$user = User::firstOrNew(['email' => request('email')]); $user->name = request('name'); $user->save()
If you cannot find an existing model, you can also pass it through the second parameter An array of additional properties:
$user = User::firstOrNew( ['email' => request('email')], ['name' => request('name')] ); $user->save();
firstOrCreate
The firstOrCreate method is very similar to the firstOrNew method. It will try to find a matching model based on the first parameter you pass. If it is not found, it will automatically create and save a new model using the value passed in the second parameter:
$user = User::firstOrCreate( ['email' => request('email')], ['name' => request('name')] ); // No call to $user->save() needed
firstOr
I recently discovered the firstOr method when I was fishing. The firstOr method will retrieve the first piece of data. If no matching data is found, the incoming callback will be executed. This is useful if you need to take extra steps when creating a user, or want to do something other than create a new user:
$user = User::where('email', request('email'))->firstOr(function () { $account = Account::create([ //... ]); return User::create([ 'account_id' => $account->id, 'email' => request('email'), ]); });
updateOrCreate
The updateOrCreate method attempts to find a model that matches the constraints passed in the first argument. If a matching model is found, it will update the model with the properties passed in the second parameter. If a matching model is not found, a new model will be created, passing in the first and second arguments.
You can refactor this code:
$user = User::where('email', request('email'))->first(); if ($user !== null) { $user->update(['name' => request('name')]); } else { $user = User::create([ 'email' => request('email'), 'name' => request('name'), ]); } // Do other things with the User
Use the updateOrCreate method:
$user = User::updateOrCreate( ['email' => request('email')], ['name' => request('name')] ); // Do other things with the User
Conclusion
In summary, I think these methods can help you simplify your code in some cases! Do you know of any other useful little-known tips? If so, please let me know. I love learning about the little details that make Laravel so great.
For more laravel framework technical articles, please visit laraveltutorial!
The above is the detailed content of firstOrNew, firstOrCreate, firstOr and updateOrCreate methods in laravel. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.

Laravel - Artisan Console - Laravel framework provides three primary tools for interaction through command-line namely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail.
