|
101 | 101 | - [Chain conditional clauses to the query without writing if-else statements](#chain-conditional-clauses-to-the-query-without-writing-if-else-statements)
|
102 | 102 | - [Override Connection Attribute in Models](#override-connection-attribute-in-models)
|
103 | 103 | - [Using Column Names in Where Clauses (Dynamic Where Clauses)](#using-column-names-in-where-clauses-dynamic-where-clauses)
|
| 104 | +- [Using firstOrCreate()](#using-firstorcreate) |
104 | 105 |
|
105 | 106 | ### Reuse or clone query()
|
106 | 107 |
|
@@ -2173,4 +2174,49 @@ class UserController extends Controller
|
2173 | 2174 | }
|
2174 | 2175 | }
|
2175 | 2176 | ```
|
| 2177 | + |
2176 | 2178 | 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