You can use firstOrCreate() to find the first record matching the attributes or create it if it doesn't exist.
Example Scenario
Assume that you are importing a CSV file and you want to create a category if it doesn't exist.
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
public function example(Request $request)
{
// Previous approach:
$category = Category::where('name', $request->name)->first();
if (!$category) {
$category = Category::create([
'name' => $request->name,
'slug' => Str::slug($request->name),
]);
}
// you can use
$category = Category::firstOrCreate([
'name' => $request->name,
], [
'slug' => Str::slug($request->name),
]);
return $category;
}
}