Skip to content

Commit 246a74b

Browse files
add using firstOrCreate() tip
1 parent 6b8629a commit 246a74b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

db-models-and-eloquent.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@
101101
- [Chain conditional clauses to the query without writing if-else statements](#chain-conditional-clauses-to-the-query-without-writing-if-else-statements)
102102
- [Override Connection Attribute in Models](#override-connection-attribute-in-models)
103103
- [Using Column Names in Where Clauses (Dynamic Where Clauses)](#using-column-names-in-where-clauses-dynamic-where-clauses)
104+
- [Using firstOrCreate()](#using-firstorcreate)
104105

105106
### Reuse or clone query()
106107

@@ -2173,4 +2174,49 @@ class UserController extends Controller
21732174
}
21742175
}
21752176
```
2177+
21762178
Tip given by [@MNurullahSaglam](https://twitter.com/MNurullahSaglam/status/1699763337586749585)
2179+
2180+
### Using firstOrCreate()
2181+
2182+
You can use firstOrCreate() to find the first record matching the attributes or create it if it doesn't exist.
2183+
2184+
#### Example Scenario
2185+
2186+
Assume that you are importing a CSV file and you want to create a category if it doesn't exist.
2187+
2188+
```php
2189+
<?php
2190+
2191+
namespace App\Http\Controllers;
2192+
2193+
use App\Models\Category;
2194+
use Illuminate\Http\Request;
2195+
2196+
class CategoryController extends Controller
2197+
{
2198+
public function example(Request $request)
2199+
{
2200+
// instead of
2201+
$category = Category::where('name', $request->name)->first();
2202+
2203+
if (!$category) {
2204+
$category = Category::create([
2205+
'name' => $request->name,
2206+
'slug' => Str::slug($request->name),
2207+
]);
2208+
}
2209+
2210+
// you can use
2211+
$category = Category::firstOrCreate([
2212+
'name' => $request->name,
2213+
], [
2214+
'slug' => Str::slug($request->name),
2215+
]);
2216+
2217+
return $category;
2218+
}
2219+
}
2220+
```
2221+
2222+
Tip given by [@MNurullahSaglam](https://twitter.com/MNurullahSaglam/status/1699773783748366478)

0 commit comments

Comments
 (0)