Урок 03

CRUD: создание и чтение

Создание

Через new

$post = new Post();
$post->title = 'Заголовок';
$post->body = 'Текст';
$post->save();

Через create

$post = Post::create([
    'title' => 'Заголовок',
    'body' => 'Текст',
]);

Метод create использует массовое присваивание, поэтому поля должны быть в $fillable.

First or Create

Если запись существует — вернуть её. Если нет — создать:

$post = Post::firstOrCreate(
    ['slug' => 'hello-world'],
    ['title' => 'Hello World']
);

Update or Create

$post = Post::updateOrCreate(
    ['slug' => 'hello-world'],
    ['title' => 'Новый заголовок']
);

Чтение

По первичному ключу

$post = Post::find(1);
$post = Post::findOrFail(1); // 404 если нет

Все записи

$posts = Post::all();

С условиями

$posts = Post::where('is_active', true)->get();
$post = Post::where('slug', 'hello')->first();
$post = Post::where('slug', 'hello')->firstOrFail();

Множество ключей

$posts = Post::find([1, 2, 3]);

Агрегаты

$count = Post::where('is_active', true)->count();
$max = Post::max('views');
$avg = Post::avg('rating');

Обновление

$post = Post::find(1);
$post->title = 'Новый';
$post->save();

$post->update(['title' => 'Ещё новее']);

Удаление

$post->delete();
Post::destroy(1);
Post::destroy([1, 2, 3]);

Обновление или создание

Метод upsert для массовых операций:

Post::upsert([
    ['id' => 1, 'title' => 'A'],
    ['id' => 2, 'title' => 'B'],
], ['id'], ['title']);

Первый массив — данные, второй — уникальные колонки, третий — колонки для обновления.