.
Laravel
Документация
Видеоуроки
Старт проекта
- 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 ./
Модули / Расширения
Запросы на чтение
$user = User::findOrFail($id); $user = User::firstOrCreate(['email' => $email]); $user = User::find(1); $users = User::find([1,2,3]);
$media = Media::find($id); $categories = Category::lists('category', 'id'); return view('medias.edit-media')->with('media', $media)->with('categories', $categories);
IN
Game::whereIn('games.id', $roomList)->get();
Column
Game::whereIn('id', $roomList)->pluck('id')->toArray();
Select fields, field
Table::select('name','surname')->where('id', 1)->get();
AsArray
Game::select('games.id as id')->whereIn('games.id', $roomList)->get()->toArray();
NotNull
Model::whereNotNull('sent_at'); DB::table('table_name')->whereNotNull('sent_at')->get();
Scalar
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');
Group where
$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();
Sub query
$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();
DB::query()->fromSub(function ($query) { $query->from('abc')->groupBy('col1'); }, 'a')->count();
Запросы на добавление/обновление
$friend = Friend::updateOrCreate( ['user_id' => $friendId, 'friend_id' => $userId], ['status' => Friend::STATUS_ACCEPTED] );
# https://laravel.com/docs/5.3/eloquent#inserting-and-updating-models
Update all
YourModelName::where(['siteView' => 6])->update(['siteView' => 7]); YourModelName::where('siteView', 6)->update(['siteView' => 7]); YourModelName::query()->update(['siteView' => 8]);
Отношения / Relations
Метод "has()"
Метод "has()" используется для проверки наличия связи между двумя моделями. Представьте себе модель "Post", которая имеет связь с моделью "Comment". Используя метод "has()", вы можете проверить, есть ли связь, прикрепленная к записи.
<?php use App\Models\Post; // Get all posts that have at least one comment $posts = Post::query() ->has('comments') ->get();
Метод "whereHas()"
Метод "whereHas()" такой же, как и метод "has()", но вы можете передать условия для запроса отношения. В примере ниже вы выполняете запрос к модели "Post", в которой отношение имеет тело, содержащее слова "hello".
<?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();
$authors = Author::whereHas('books', function (Builder $query) { $query->where('title', 'like', 'PHP%'); })->get();
Метод "withWhereHas()"
use Illuminate\Database\Eloquent\Builder; Builder::macro('withWhereHas', fn($relation, $constraint) => $this->whereHas($relation, $constraint)->with([$relation => $constraint]); );
$books = Book::withWhereHas('author.awards', function ($query) { $query->where('year', now()->format('Y')); })->get();
Метод "with()"
Метод "with()" используется для нетерпеливой загрузки связи Eloquent, чтобы предотвратить проблему N+1, часто встречающуюся при запросе записи. Как правило, рекомендуется использовать метод "with()", когда вы запрашиваете Eloquent, имеющий связь.
$filter = function ($query) { $query->where('year', now()->format('Y')); }; $books = Book::with(['author.awards' => $filter]) ->whereHas('author.awards', $filter) ->get();
<?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();
$books = Book::with(['author.awards' => function ($query) { $query->where('year', now()->format('Y')); }])->get();
$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();
$filter = function ($query) { $query->where('year', now()->format('Y')); }; $books = Book::with(['author.awards' => $filter]) ->whereHas('author.awards', $filter) ->get();
Метод "load()"
Наконец, метод «load()» аналогичен методу «with()», в котором он используется для активной загрузки отношения Eloquent, но его следует использовать, когда у вас уже есть существующий экземпляр Eloquent, например, как показано ниже.
<?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);
Заполнение/обновление/проверка пивот таблиц
$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)
Increment
$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
Запросы на удаление
$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();
Transactions
app('db')->beginTransaction(); app('db')->commit(); app('db')->rollBack();