- firstOrCreate()
- updateOrCreate()
Laravel FirstOrCreate Method
This method allows you to retrieve the first model of the given condition if available, otherwise a new model instance will be created and stored in the database.
<?php $post = Post::firstOrCreate(['title' => 'post 2']); // if 'post 1' exists the it will be retrieved // otherwise 'post 1' doesn't exists, 'post 2' will be created
A more complex condition to retrieve the model will be like below.
<?php Post::where('slug', 'post-1') ->whereNotNull('summary') ->firstOrCreate([/* your content here*/]);
Laravel UpdateOrCrate Method
For this method, you can update the existing model or create a new modal.
Post::updateOrCreate(['slug' => 'post-1'], ['slug' => 'post-1', 'summary' => 'hello world']);
The code above will try to update the post with a slug called 'post-1' with the value of the summary. If it doesn't exists then the new post will be created,
Leave a reply