{{tag>laravel framework php}}

{{backlinks>.}}

====== Laravel ======

{{:undefined:laravel.png?400|}}

{{::laravel-request-life-cycle.png?800|}}

===== Документация =====

  * https://laravel.su/docs/11.x/releases (RU)
  * https://laravel-docs.com/ru/docs/10.x/releases (RU)
  * [[:php:laravel:relations]]
  * https://laravel.com/docs/11.x/releases (EN)
  * https://www.slingacademy.com/article/when-to-use-and-when-not-to-use-laravel/

===== Видеоуроки =====

  * [[https://www.youtube.com/playlist?list=PLze7bMjv1CYtGKFuL_8G0OxsSMmvHE6Xc|Курс по Laravel для начинающих]]
  * [[https://www.youtube.com/playlist?list=PLoonZ8wII66h2eXaNdSATK8zkFQ4LxUmt|Laravel - October CMS]]
  * [[https://www.youtube.com/playlist?list=PLoonZ8wII66g5zNGjbHiapYZfnX106lRN|October CMS - Создание компонент]]
  * [[https://www.youtube.com/playlist?list=PLXCVm4GFpx5DMQeuzyQwZW8QtslxsUxFy|Laravel Helpers]]
  * [[https://www.youtube.com/playlist?list=PL3-0tsv0n0zYa0nNtDzq0kS-Ha6l95w3X|Laravel уроки]]
  * [[https://www.youtube.com/playlist?list=PLNvHH49JXUUCeFbIl23lHCLO1tTmKWBtn|Фреймворк Laravel]]
  * [[https://www.youtube.com/playlist?list=PLTucyHptHtTkUbXaikXEmCWL8GradRx9I|Курс по Laravel 8 обучение с нуля. Бесплатные видеоуроки по Ларавел для начинающих]]
  * [[https://www.youtube.com/playlist?list=PL8jSdafHd96wsHGWVlS3_BxHS5FJ4ReND|Курс по Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t9xFti7HJm8-hAM0XAjzQim|Платные практические курсы]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t9UEjGQHafQB751mf5cwqNv|Шаг 5. Laravel курс. Интернет Магазин]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t8foG_gKb31q7xnAtaOCFBw|Шаг 4.3. CI/CD в целом и CI/CD для Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t9Ert8mBlNl1UqwllyP1Tm_|Шаг 4.2. Docker в целом и Docker для Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t-Dy5nO8CnPEvH_ERwZzDSk|Шаг 3.3. Полный курс Laravel Vue работа с Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t9g9HYi_MyogUfuGeHMjFqF|Шаг 3.2. Курс Laravel Sanctum c vuejs]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t8OTGDdiHJdS3gkdoKajpX9|Шаг 3.1. Курс JWT с Vuejs для Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t8XxpP2j3-Jy90jSJftNsOC|Шаг 3. Курс Js и Vuejs для Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t8StX6GztbdMIUXmgPuingB|Шаг 2. Laravel курс. Блог]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t8pnG4ubQemoqnTwf0VFEtU|Laravel курс с нуля, база. 0. Первый проект на Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t-Q2S8Cgo6a41rvee0f_sCG|SQL курс для Laravel]]
  * [[https://www.youtube.com/playlist?list=PLd2_Os8Cj3t-CoUEdoAiYc1sj21FH79no|PHP курс для Laravel с нуля]]
  * [[https://www.youtube.com/playlist?list=PLXCVm4GFpx5CZf4X5ppNJTPsaGwSlBXLX|Laravel (полный курс 2023)]]
  * [[https://www.youtube.com/playlist?list=PLoonZ8wII66iP0fJPHhkLXa3k7CMef9ak|Laravel 8 - Видеокурс]]


===== Старт проекта =====

  * composer create-project laravel/laravel ./laravel
  * composer create-project --prefer-dist laravel/laravel:^7.0 ./blo
  * composer create-project --prefer-dist laravel/laravel ./laravel
  * composer create-project laravel/laravel {directory} "5.0.*" --prefer-dist
  * composer create-project spatie/package-skeleton-laravel ./

===== Модули / Расширения  =====

  * https://github.com/Askedio/laravel-soft-cascade
  * https://github.com/Mirocow/laravel-rabbitmq

===== Запросы на чтение =====

<code php>
$user = User::findOrFail($id);
$user = User::firstOrCreate(['email' => $email]);
$user = User::find(1);
$users = User::find([1,2,3]);
</code>

<code php>
$media = Media::find($id);
$categories = Category::lists('category', 'id');
return view('medias.edit-media')->with('media', $media)->with('categories', $categories);
</code>
==== IN ====

<code php>Game::whereIn('games.id', $roomList)->get();</code>

==== Column ====

<code php>Game::whereIn('id', $roomList)->pluck('id')->toArray();</code>

==== Select fields, field ====

<code php>Table::select('name','surname')->where('id', 1)->get();</code>

==== AsArray ====

<code php>Game::select('games.id as id')->whereIn('games.id', $roomList)->get()->toArray();</code>

==== NotNull ====

<code php>
Model::whereNotNull('sent_at');
  
DB::table('table_name')->whereNotNull('sent_at')->get();  
</code>

==== Scalar ====

<code php>
Model::whereNotNull('sent_at');
  
DB::table('table_name')->where('id' = 1)->get();  

$count = App\Flight::where('active', 1)->count();

$max = App\Flight::where('active', 1)->max('price');
</code>

==== Group where ====

<code php>
$results = DB::table('table')
             ->where(function($query) use ($starttime,$endtime){
                 $query->where('starttime', '<=', $starttime);
                 $query->where('endtime', '>=', $endtime);
             })
             ->orWhere(function($query) use ($otherStarttime,$otherEndtime){
                 $query->where('starttime', '<=', $otherStarttime);
                 $query->where('endtime', '>=', $otherEndtime);
             })
             ->orWhere(function($query) use ($anotherStarttime,$anotherEndtime){
                 $query->where('starttime', '>=', $anotherStarttime);
                 $query->where('endtime', '<=', $anotherEndtime);
             })
             ->get();
</code>

==== Sub query ====

<code php>
$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )

    // ->where(..) wrong

    ->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder

    // ->where(..) correct

    ->count();
</code>

<code php>
DB::query()->fromSub(function ($query) {
    $query->from('abc')->groupBy('col1');
}, 'a')->count();
</code>
===== Запросы на добавление/обновление =====

<code php>
$friend = Friend::updateOrCreate(
    ['user_id' => $friendId, 'friend_id' => $userId],
    ['status' => Friend::STATUS_ACCEPTED]
);
</code>
# https://laravel.com/docs/5.3/eloquent#inserting-and-updating-models

==== Update all ====

<code php>
YourModelName::where(['siteView' => 6])->update(['siteView' => 7]);
YourModelName::where('siteView', 6)->update(['siteView' => 7]);
YourModelName::query()->update(['siteView' => 8]);
</code>

==== Отношения / Relations ====

=== Метод "has()" ===

Метод "has()" используется для проверки наличия связи между двумя моделями. Представьте себе модель "Post", которая имеет связь с моделью "Comment". Используя метод "has()", вы можете проверить, есть ли связь, прикрепленная к записи.

<code php>
<?php

use App\Models\Post;

// Get all posts that have at least one comment
$posts = Post::query()
    ->has('comments')
    ->get();
</code>

=== Метод "whereHas()" ===

Метод "whereHas()" такой же, как и метод "has()", но вы можете передать условия для запроса отношения. В примере ниже вы выполняете запрос к модели "Post", в которой отношение имеет тело, содержащее слова "hello".

<code php>
<?php

use App\Models\Post;

// Get posts with at least one comment containing words like hello%
$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('body', 'like', 'hello%');
})->get();
</code>

<code php>
$authors = Author::whereHas('books', function (Builder $query) {
 $query->where('title', 'like', 'PHP%');
})->get();
</code>

=== Метод "withWhereHas()" ===

<code php>
use Illuminate\Database\Eloquent\Builder;

Builder::macro('withWhereHas', fn($relation, $constraint) =>
 $this->whereHas($relation, $constraint)->with([$relation => $constraint]);
);
</code>

<code php>
$books = Book::withWhereHas('author.awards', function ($query) {
    $query->where('year', now()->format('Y'));
})->get();
</code>

=== Метод "with()" ===

Метод "with()" используется для нетерпеливой загрузки связи Eloquent, чтобы предотвратить проблему N+1, часто встречающуюся при запросе записи. Как правило, рекомендуется использовать метод "with()", когда вы запрашиваете Eloquent, имеющий связь.

<code php>
$filter = function ($query) {
    $query->where('year', now()->format('Y'));
};

$books = Book::with(['author.awards' => $filter])
    ->whereHas('author.awards', $filter)
    ->get();
</code>

<code php>
<?php

use App\Models\Post;

// Eager-load the comments relation to prevent N+1 problem
Post::with('comments')->get();

// If you want to eager-load nested relation then you can use the "." dot notation
Post::with('comments.likes')->get();
</code>

<code php>
$books = Book::with(['author.awards' => function ($query) {
    $query->where('year', now()->format('Y'));
}])->get();
</code>

<code php>
$books = Book::with(['author.awards' => function ($query) {
    $query->where('year', now()->format('Y'));
}])->whereHas('author.awards', function ($query) {
    $query->where('year', now()->format('Y'));
})->get();
</code>

<code php>
$filter = function ($query) {
    $query->where('year', now()->format('Y'));
};

$books = Book::with(['author.awards' => $filter])
    ->whereHas('author.awards', $filter)
    ->get();
</code>

=== Метод "load()" ===

Наконец, метод «load()» аналогичен методу «with()», в котором он используется для активной загрузки отношения Eloquent, но его следует использовать, когда у вас уже есть существующий экземпляр Eloquent, например, как показано ниже.

<code php>
<?php

use App\Models\Post;

// get the first post
$post = Post::find(1);

// by now it's not possible to call the "with()" method because it's a static method. To eager load at this point you can call the "load()" method from your existing model instance.
$post = $post->load("comments');

// now your $post model will have the "comments" relationship loaded as well.
dd($post);
</code>

==== Заполнение/обновление/проверка пивот таблиц ====

<code php>
$room->games()->attach($gameId);
$owner->rooms()->attach($room->id, ['is_admin' => true]);
$user->roles()->updateExistingPivot($roleId, $attributes);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

$user->roles()->attach($roleId);
$user->roles()->attach($roleId, [‘expires’ => $expires]);

App\User::find(1)->roles()->save($role, ['expires' => $expires]);

$user->roles()->toggle([1, 2, 3]);

$messages  = Message::where('message_id', $id)->get();
foreach($messages as $message) {
   $message->users()->updateExistingPivot($user, array('status' => 1), false);
}   
   
$items = $invoice->items->pluck('name', 'id')->toArray();
foreach ($items as $key => $item) {
    $invoice->items()->updateExistingPivot($key, ['quantity' => $request->quantity]);
}

$user->rooms()->get()->contains($room->id)  
</code> 

==== Increment ====

<code php>
$article = Article::find($article_id);
$article->increment('read_count');

Article::find($article_id)->increment('read_count');
Article::find($article_id)->increment('read_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1
</code>

===== Запросы на удаление =====

<code php>
$ids = array(10, 20, 30);
DB::table('table_name')->whereIn('id', $ids)->delete();

MyModel::truncate();

\App\Model::query()->delete();

DB::statement("SET foreign_key_checks=0");
Model::truncate();
DB::statement("SET foreign_key_checks=1");

DB::table('table_name')->truncate();

DB::table('table_name')->delete();

Model::whereRaw('1=1')->delete();

User:where('id', 'like' '%%')->delete();

DB::table('users')->whereIn('id', $ids_to_delete)->delete();
</code>
===== Transactions =====

<code php>
app('db')->beginTransaction();
app('db')->commit();
app('db')->rollBack();
</code>

