20210503のlaravelに関する記事は9件です。

EC2にPHPでWebAPIをサクッと作る

やりたいこと 検証用のEC2にWebAPIをサクッと作る PHPで実装 クライアントの要望でEC2上にPHPで簡単なRestAPIを作成することになった。 作成するのはPostとPutの2つのAPIのみ。 PHP自体が初なのでそもそもの実現方法から検討。 調べたところ生のPHPでもroutingなどは行えそうではあったが、Larvelの軽量フレームワークLumenであれば割と手軽に入れて実装自体も簡単そうだったので今回はLumenで対応。 https://lumen.laravel.com/ 手順 1. EC2にapacheをインストール まずは更新 sudo yum update -y 次にインストール sudo yum install httpd 2. EC2にphpをインストール EC2用のPHPを入れることで7系のPHPのインストールが行える。 (LumenがPHP7.3以降しか対応していない) sudo amazon-linux-extras install php7.4 -y 4. EC2にcomposerをインストール Lumenを利用するために必要なcomposerをインストールする。 公式サイトに記載があるコマンドをコピペして実行 https://getcomposer.org/download/ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');" composerの本体はbin以下においておく sudo mv composer.phar /usr/local/bin/composer 5. Lumenのセットアップ まずはLumenで必要なライブラリをインストール sudo yum install php-mbstring php-pecl-memcached php-gd php-apcu php-xml -y 続いてLumenを入れていく composer global require "laravel/lumen-installer=~1.0" プロジェクトの雛形を作成する cd /var/www/html lumen new blog ※上記のコマンドの最後のblogがフォルダ名になるので自由に変える ※apache上で動かすので /var/www/html 配下に作成した。 なお、Lumenを入れずにcomposerの以下のコマンドでもプロジェクトの雛形は作成可能 composer create-project --prefer-dist laravel/lumen blog 6. 権限設定 Lumenのログとキャッシュのフォルダに書き込み権限を付与する。 これやらないとログが出せない。 cd /var/www/html/blog chmod -R 777 bootstrap chmod -R 777 storage 7. Apache Virtual Hostの設定 /etc/httpd/conf.d以下にvhost.confを作成する。 ※ファイル名は拡張子が.confであればなんでもOK 中身を記載する ※DocumentRootとServerNameでどのドメインでアクセスされたらどこをDocumentRootにするかを指定するための設定 <VirtualHost *:80> DocumentRoot /var/www/html/blog/public ServerName [EC2のパブリックDNS名称] <Directory "/var/www/html/blog/public"> # allow .htaccess AllowOverride All # Setting Laravel environment SetEnv APP_ENV development # Allow access Require all granted </Directory> </VirtualHost> 一旦これでポート80のhttpの通信に対応できるようになる。 Direcory以下を記載しないとRestのRountingが動かないので記載する。 APP_ENVとかは多分なくても動く。 ドメイン直下にアクセスするとLumenのバージョンが表示される。 Lumen (8.2.3) (Laravel Components ^8.0) 8. 完了 これで一通りの設定は完了 あとは好きなように実装するのみ。 参考 https://qiita.com/miriwo/items/b25f9d4d74b7103f6ff6
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

6 Questions for Every PHP Developer in Laravel Interview

Going to give a "Laravel developer interview" is the so-called complicated thing for all those professionals who are good in practical things but zero in theory. We know developers are reasonably realistic, and they are only focused on real-time approaches for career goals. Still, the idea also has vital importance that you ignore in the 21st century. Here I will share the six questions for every PHP developer in Laravel Interview that you can't miss for your successful job interview behind recruiter. 6 Questions for Every PHP Developer in Laravel Interview 1). Can You Define What Laravel Is? Stop! Don't think they are asking something unmatchable from your profiles. Dear, they are only asking for the definition of Laravel but in a quite compelling manner. Your Laravel interview is not the high-school-based exam in which you will get answers like what is the meaning of Laravel? In professional talks, the format of asking questions is quite different from the usual question. Thus, the interviewer never asks directly about the definition of the Laravel Framework, and they use some other way to ask questions. What Answer do You Need to Give? An open-source PHP framework design on the MVC pattern is known as PHP. Taylor Otwell creates the framework, and this is the most eminent application for the blossom web application. 2). What are the Merits and Demerits of Laravel? The interviewer's next question can also ask from a PHP Developer is about the merits and demerits. When you want to become a Laravel Developer, you need to know the complete information of the program. Here I will discuss some pros and cons of Laravel that you can use in your interview for a good impression. Merits of Laravel Framework: 1). For the dynamic content goals, heavy blade template not worthy, and that's why Laravel Framework is the lightweight blade template-based framework to create high-profile real-time content layouts. 2). Code Readability is Hassle-Free 3). PHP framework built-in with Command Line Tool "Artisan" for developing Demerits of PHP: 1). Deep knowledge or programming is a must to work on PHP frameworks, and beginners can't deliver the best results 2). Ruby Gems and Python are the main competitors of Laravel 3). Development is not relatively less time-consuming process in the Laravel framework 4). Laravel comes with less inbuilt support 3). What do you mean by Events in Laravel? An application required actions that are the outcomes of events in the framework. Event is a crucial aspect attached to a program that can handle code. For smoother implementation, we required events. 4). Where to Store Events? Events Classes are mainly available in Events Directory or Apps Directory. Sometimes, beginners don't know the correct answer to this question, and that's why they can't answer this question. Laravel Development Company always tries to hire an excellent candidate for the position of Laravel Developer. 5). Are there any Validations in Laravel or Not? Validations are the most critical aspect of any program. The primary purpose of confirmations is to clean and code in the correct format. We can also say that the code structure also depends on the developer's assurances for Laravel App Development. That means a developer must be efficient in applying good warranties. You can find many ways to use validation in Laravel. 6). Had You Ever Work on Laravel Project or Not? One of the challenging questions for PHP Developers in Laravel Interview is your work experience on the Laravel Projects. Had you ever worked or not in this framework project is also the main requirement of the company. For Laravel Development Services, they need a perfect candidate for a company that had already work on this framework. Now the question is how to answer when you do not handle a single project in Laravel? You can also explain your PHP Experience and mention how passionate you are about developing Laravel Framework. Primary Industries and Social Media Platforms Developed in Laravel: There is no doubt that Laravel is a framework in the 21st century used in many various industries for development purposes. Gone were the days when developers have only one or two programming language skills. Nowadays, a developer has many programming language skills. Development of applications means never stop learning, and if you stop learning, then you may never be able to get success in this industry. Key-Reasons to go with Laravel Development Services: Here you also need to know about the key reason to go with Laravel Development Services. No matter you are technical or non-technical? Fast Web and Mobile Applications are the demand of industry and clients. Laravel provides this opportunity to developers for making excellent quality applications with fast speed. Training Programs Also Conducted By Companies: To skilled developers in various programming languages, companies also conducted skill training programs to switch development frameworks. As a PHP Developer, switching to Laravel is quite tricky initially. You may face so many problems in developing applications or frameworks but don't worry. This can only happen in the beginning time. Once time passes, you will know about things automatically in a short period. Many multinational companies focus on training and skill programs for the developers, and that's why they want to improve workforce skills by using training programs. Summary: Why do you need to know about these six questions as a PHP Developer when you are going to give a Laravel Developer Interview? To justify your knowledge and skill behind the recruiter, you need to know about these questions. Thus, we already state these questions briefly, and we hope this information is useful for your Laravel Developer Interview. You can also answer these questions according to your knowledge and opinion because we only give ideas here. Laravel is an excellent framework for people to establish a portal with advanced functionality and flexibility. Laravel also allows for an easy content management system for the users. These 6 questions are helpful for all those developers who are going to give interviews for Laravel Development.
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel リレーションのまとめ(一対多 多対多 )

リレーションについて毎回調べてしまっていることが多いので、内容整理として。 (随時更新) 前提 バージョン:Laravel6 一対多 ①一対多とは 一対多のリレーションとは、あるmodelインスタンス一つ(ModelA)に対して複数のmodelインスタンス(ModelB)が紐づく関係のこと。その「紐づき」にあたるものが外部キー。あるModelAインスタンスには複数のModelBインスタンスが紐づくが、あるModelBインスタンスは特定のModelAインスタンスにだけ紐づく。 ②migration create_model_a_table.php //ModelAマイグレーション public function up() { Schema::create('model_a', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->timestamps(); }); } create_model_b_table.php //ModelBマイグレーション public function up() { Schema::create('model_b', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('model_a_id'); // 外部キー $table->string('name'); $table->timestamps(); // 外部キー制約 $table->foreign('model_a_id')->references('id')->on('model_a')->onDelete('cascade'); }); } 外部キー制約はforeign('外部キー')->references('参照先のカラム')->on('参照テーブル')と記述する。 onDelete('**')はデータ削除時の振舞いを指定するもの。 cascade:参照先が削除されると、共に削除される。 set null:参照先が削除されると、外部キーがnullになる。 restrict:参照先が削除されると、エラーを返す。 ③model ModelA.php // このインスタンスに紐づくModelBインスタンス public function modelBs() { return $this->hasMany(ModelB::class); } // このインスタンスに紐づくインスタンスの数を取得する。 public function loadRelationshipCounts() { $this->loadCount('modelBs'); } ModelB.php // このインスタンスに紐づくModelAインスタンス public function modelA() { return $this->belongsTo(ModelA::class); } 多対多 ①多対多とは 多対多のリレーションとは、あるmodelインスタンス群(ModelC)に対して複数のmodelインスタンス群(ModelD)が紐づく関係のこと。一対多とは異なり、あるModelCインスタンスが複数のModelDインスタンスと紐づくだけでなく、あるModelDインスタンスが複数のModelCインスタンスと紐づくことができる。 多対多を実現するには中間テーブルを用いる。 ②migration create_model_c_table.php //ModelCマイグレーション public function up() { Schema::create('model_c', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->timestamps(); }); } create_model_d_table.php //ModelDマイグレーション public function up() { Schema::create('model_d', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->timestamps(); }); } create_relay_c_d_table.php //中間テーブルマイグレーション public function up() { Schema::create('relay_c_d', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('model_c_id'); // 外部キー $table->unsignedBigInteger('model_d_id'); // 外部キー $table->string('name'); $table->timestamps(); // 外部キー制約 $table->foreign('model_a_id')->references('id')->on('model_c')->onDelete('cascade'); $table->foreign('model_a_id')->references('id')->on('model_d')->onDelete('cascade'); }); } 外部キー制約はforeign('外部キー')->references('参照先のカラム')->on('参照テーブル')と記述する。 onDelete('**')はデータ削除時の振舞いを指定するもの。 cascade:参照先が削除されると、共に削除される。 set null:参照先が削除されると、外部キーがnullになる。 restrict:参照先が削除されると、エラーを返す。 ③model ModelC.php // このインスタンスに紐づくModelDインスタンス public function modelDs() { return $this->belongsToMany(ModelB::class, 'relay_c_d', 'model_c_id', 'model_d_id')->withTimestamps(); } // このインスタンスに紐づくインスタンスの数を取得する。 public function loadRelationshipCounts() { $this->loadCount('modelDs'); } ModelD.php // このインスタンスに紐づくModelCインスタンス public function modelCs() { return $this->belongsToMany(ModelC::class, 'relay_c_d', 'model_d_id', 'model_c_id')->withTimestamps(); } // このインスタンスに紐づくインスタンスの数を取得する。 public function loadRelationshipCounts() { $this->loadCount('modelCs'); }
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelのポリシーを使用してみた

Laravelには認可機能として「ゲート」と「ポリシー」が用意されています。 「ゲート」は下記の記事で試してみたので、今回は「ポリシー」を試してみます。 ポリシーの生成 artisanコマンドでポリシーを生成できます。--modelオプションを使用すればモデルに関連付けたポリシーを生成することができます。 php artisan make:policy ArticlePolicy --model=Article artisanコマンドを実行するとapp/Policiesディレクトにファイルが生成されます。生成されたファイルにはいくつかのメソッドがあらかじめ作られています。 app/Policies/ArticlePolicy.php <?php namespace App\Policies; use App\Models\Article; use App\Models\User; use Illuminate\Auth\Access\HandlesAuthorization; class ArticlePolicy { use HandlesAuthorization; /** * Determine whether the user can view any models. * * @param \App\Models\User $user * @return mixed */ public function viewAny(User $user) { // } /** * Determine whether the user can view the model. * * @param \App\Models\User $user * @param \App\Models\Article $article * @return mixed */ public function view(User $user, Article $article) { // } /** * Determine whether the user can create models. * * @param \App\Models\User $user * @return mixed */ public function create(User $user) { // } /** * Determine whether the user can update the model. * * @param \App\Models\User $user * @param \App\Models\Article $article * @return mixed */ public function update(User $user, Article $article) { // } /** * Determine whether the user can delete the model. * * @param \App\Models\User $user * @param \App\Models\Article $article * @return mixed */ public function delete(User $user, Article $article) { // } /** * Determine whether the user can restore the model. * * @param \App\Models\User $user * @param \App\Models\Article $article * @return mixed */ public function restore(User $user, Article $article) { // } /** * Determine whether the user can permanently delete the model. * * @param \App\Models\User $user * @param \App\Models\Article $article * @return mixed */ public function forceDelete(User $user, Article $article) { // } } ポリシーを使用したアクションの認可 ここから、ポリシーを使用してユーザーにある操作の許可・拒否を実装していきます。例えば記事の更新は、記事を作成したユーザーのみしかできないようにしてみます。 app/Policies/ArticlePolicy.php /** * Determine whether the user can update the model. * * @param \App\Models\User $user * @param \App\Models\Article $article * @return mixed */ public function update(User $user, Article $article, $category, $role) { return $user->id === $article->user_id; } 定義したアクションは、 ユーザーモデル経由 コントローラヘルパ経由 ミドルウェア経由 Bladeテンプレート経由 で呼び出せます。 ユーザーモデル経由 App\Models\Userモデルにはアクションを認可するための特別なメソッドcan・cannotが含まれていて、これらのメソッドを使用することでアクションを認可することができます。 app/Http/Controllers/ArticlesController.php public function edit(Request $request, Article $article) { if ($request->user()->cannot('update', $article)) { abort(403); } return view('articles.edit', ['article' => $article]); } コントローラヘルパ経由 コントローラからauthorizeメソッドを呼び出すことによっても、アクションを認可することができます。 app/Http/Controllers/ArticlesController.php public function edit(Request $request, Article $article) { $this->authorize('update', $article); return view('articles.edit', $article); } ミドルウェア経由 canミドルウェアを使用することで、アクションの認可ができます。 routes/web.php Route::get('/article/edit/{article}', 'App\Http\Controllers\ArticlesController@edit') ->middleware(['auth']) ->middleware('can:update,article'); Bladeテンプレート経由 bladeテンプレート内で@canまたは@cannotディレクティブを使用することで、アクションを認可できます。 edit.blade.php @can('update', $article) <input type="submit" value="send"> @else <h3>更新できません</h3> @endcan ポリシーフィルター ポリシーファイルでbeforeメソッドを定義すると、ほかのポリシーメソッドが呼び出される前に実行されます。例えばadminユーザーはすべてのアクションを許可したいとなった場合、 app/Policies/ArticlePolicy.php public function before(User $user, $ability) { if ($user->role === 'admin') { return true; } } このように定義するとadminユーザーをすべてのアクションが許可されます。 ポリシーメソッドに追加のパラメータを渡す 例えば、あるカテゴリーの記事に関してはすべてのユーザーが更新できるようにしたいとなった場合、 ArticlePolicy.php /** * Determine whether the user can update the model. * * @param \App\Models\User $user * @param \App\Models\Article $article * @return mixed */ public function update(User $user, Article $article, $category) { return $user->id === $article->user_id || $category === 'free'; } このように、updateメソッドの第3引数に$categoryを追加します。ポリシーを呼び出す側では、 ArticlesController.php public function edit(Request $request, Article $article) { $this->authorize('update', [$article, $request->category]); return view('articles.edit', $article); } このように、最初の引数にアクション名を渡し2番目の引数に配列を渡します。配列の1番目には、どのポリシーを使用するかを指定し、2番目以降にポリシーメソッドに渡すパラメータを指定します。 おまけ ポリシーを使用するにあたって、認証機能・必要なテーブルデータを用意する必要がある場合は下記の記事を参考に。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelで簡単なCMSを作成(記事へのタグ付け)

Laravelで簡単なCMSを作成してみます。 環境構築から記事の登録・更新は下記の記事を参考にどうぞ。 今回は、作成した記事にタグを付けてみます。 リソースコントローラ作成 Laravelのartisanコマンドを使ってリソースの作成、読み取り、更新、または削除を処理するコントローラを作成できます。 Tagモデルをリソースとして、作成・読み取りができるように下記コマンドを実行してリソースコントローラーとモデルを作成します。 php artisan make:controller TagsController --resource --model=Tag php artisan make:model Tag TagsControllerを作成したらindex・create・storeメソッドを追加します。 app/Http/Controllers/TagsController.php <?php namespace App\Http\Controllers; use App\Models\Tag; use Illuminate\Http\Request; class TagsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $tags = Tag::all(); return view('tags.index', ['tags' => $tags]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('tags.add'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $article = new Tag; $article->title = $request->title; $article->save(); return redirect('/tags'); } // その他のメソッド } リソースルートを登録します。 routes/web.php use App\Http\Controllers\TagsController; Route::resource('tags', TagsController::class); 以下のルートが自動的に作成されます。 動詞 URI アクション ルート名 GET /tags index tags.index GET /tags/create create tags.create POST /tags store tags.store GET /tags/{tag} show tags.show GET /tags/{tag}/edit edit tags.edit PUT/PATCH /tags/{tag} update tags.update DELETE /tags/{tag} destroy tags.destroy このうち今のところ、index・create・store以外は使用しないのでルートから除外します。 routes/web.php // Route::resource('tags', TagsController::class); Route::resource('tags', TagsController::class)->only([ 'index', 'create', 'store', ]); Viewを作成 add.blade.phpとindex.blade.phpを作成してtagの登録から一覧で確認できるようにします。 resources/views/tags/index.blade.php <x-app-layout> <x-slot name="header"> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> {{ __('Tags') }} </h2> </x-slot> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div class="p-6 bg-white border-b border-gray-200"> <table class="table-auto"> <thead> <tr> <th>Title</th> <th>Updated</th> </tr> </thead> <tbody> @foreach($tags as $tag) <tr> <td>{{$tag->title}}</td> <td>{{$tag->updated_at}}</td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </x-app-layout> resources/views/tags/add.blade.php <x-app-layout> <x-slot name="header"> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> {{ __('Tags') }} </h2> </x-slot> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div class="p-6 bg-white border-b border-gray-200"> <form action="/tags" method="post"> @csrf <div class="grid grid-cols-1 gap-6"> <label class="block"> <span class="text-gray-700">Title</span> <input type="text" name="title" class="mt-1 block w-full"> </label> <input type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" value="send"> </div> </form> </div> </div> </div> </div> </x-app-layout> /tags/createにアクセスしてtagをいくつか登録します。 記事とタグを関連付ける 記事の登録と更新画面にタグを選択できるようにします。articles/add.blade.phpとarticles/edit.blade.phpに以下のようにtag用のチェックボックスを追加します。 <label class="block"> <span class="text-gray-700">Tag</span> <select class="mt-1 block w-full" rows="3" name="tags"> @foreach($tags as $tag) <option value="{{$tag->id}}">{{$tag->title}}</option> @endforeach </select> </label> モデルを関係付ける articlesテーブルとtagsテーブルを関連付けます。1記事に複数タグ付けすることができ、また1つのタグに対して複数の記事を関連付けることができるので、articlesテーブルとtagsテーブルは多対多の関係になります。多対多の関係はbelongsToManyメソッドで定義します。 ArticleModelのほうにbelongsToManyメソッドでtagsテーブルと関連付けます。 app/Models/ArticleModel.php use App\Models\Tags; public function tags() { return $this->belongsToMany(Tag::class); } 中間テーブルに登録する 多対多の関係であるarticlesテーブルとtagsテーブルを関連付けるために中間テーブルのarticle_tagテーブルを使用します。記事の作成・更新時に中間テーブルにデータを更新していきます。attachメソッドを使用することでリレーションの中間テーブルにデータを挿入できます。syncメソッドを使用すると、引数に渡されたIDが中間テーブルに登録され、引数に渡されなかったIDは中間テーブルから物理削除されます。 リレーションの更新処理をArticlesControllerに追加します。 app/Http/Controllers/ArticlesController.php public function create(Request $request) { $article = Article::create([ 'title' => $request->title, 'body' => $request->body, 'user_id' => Auth::id(), 'slug' => $request->title, ]); // 中間テーブルにtagを登録 $article->tags()->attach($request->tags); return redirect('/articles'); } public function update(Request $request, Article $article) { $article->fill($request->all())->save(); $article->tags()->sync($request->tags); return redirect('/articles'); } 中間テーブルへの登録時にtimestampを追加する場合は、withTimestampsメソッドを使用します。 app/Models/ArticleModel.php <?php namespace App\Models; use App\Models\Tag; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Article extends Model { use HasFactory; protected $fillable = [ 'title', 'body', 'slug', 'user_id', ]; protected $casts = [ 'user_id' => 'integer' ]; public function tags() { return $this->belongsToMany(Tag::class)->withTimestamps(); } } 一覧ページ修正 記事一覧ページに、記事に関連付けられているタグも表示させます。 resources/views/articles/index.blade.php <table class="table-fixed"> <thead> <tr> <th class="w-1/4">Title</th> <th class="w-1/4">Tag</th> <th class="w-1/4">Author</th> <th class="w-1/4">Updated</th> </tr> </thead> <tbody> @foreach($articles as $article) <tr> <td><a href="/article/edit/{{$article->id}}">{{$article->title}}</a></td> <td> @foreach($article->tags as $tag) <div> {{$tag->title}} </div> @endforeach </td> <td>{{$article->user_id}}</td> <td>{{$article->updated_at}}</td> </tr> @endforeach </tbody> </table> N + 1問題 laravelの動的プロパティは「遅延読み込み」なので、N+1問題が発生します。今回のように動的プロパティにアクセスすることが分かっている場合は、Eagerロードを使用してあらかじめモデルをロードすることでN+1問題を回避することができます。 記事一覧取得時にEagerロードを使用する場合と使用しない場合で発行されるSQLを比較してみます。まずEagerロードを使用しない場合、 app/Http/Controllers/ArticlesController.php public function index() { $articles = Article::all(); return view('articles.index', ['articles' => $articles]); } 発行されるSQLは、まず select * from "articles" で記事を全件取得しその後記事ごとに、 select "tags".*, "article_tag"."article_id" as "pivot_article_id", "article_tag"."tag_id" as "pivot_tag_id", "article_tag"."created_at" as "pivot_created_at", "article_tag"."updated_at" as "pivot_updated_at" from "tags" inner join "article_tag" on "tags"."id" = "article_tag"."tag_id" where "article_tag"."article_id" = article_id が発行されます。合計で記事の件数 + 1本のSQLが発行されます。 一方、Eagerロードを使用した場合、 app/Http/Controllers/ArticlesController.php public function index() { // $articles = Article::all(); $articles = Article::with('tags')->get(); return view('articles.index', ['articles' => $articles]); } 発行されるSQLは2本となり激減します。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelで簡単なCMSを作成(記事を更新)

Laravelで簡単なCMSを作ってみます。 環境構築から記事の登録までは以下の記事を参考にどうぞ。 今回は記事の更新処理を処理を作ってみます。 Controllerを作成 ArticlesControllerにeditとupdateメソッドを追加します。 app/Http/Controllers/ArticlesController.php <?php namespace App\Http\Controllers; use App\Models\Article; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; class ArticlesController extends Controller { // 記事の登録処理など public function edit(Article $article) { return view('articles.edit', ['article' => $article]); } public function update(Request $request, Article $article) { $article->fill($request->all())->save(); return redirect('/articles'); } } Viewを作成 更新ページを用意します。 resources/views/articles/edit.blade.php <x-app-layout> <x-slot name="header"> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> {{ __('Articles') }} </h2> </x-slot> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div class="p-6 bg-white border-b border-gray-200"> <form action="/article/update/{{$article->id}}" method="post"> @csrf <div class="grid grid-cols-1 gap-6"> <label class="block"> <span class="text-gray-700">Title</span> <input type="text" name="title" class="mt-1 block w-full" value="{{$article->title}}"> </label> <label class="block"> <span class="text-gray-700">Body</span> <textarea class="mt-1 block w-full" rows="3" name="body">{{$article->body}}</textarea> </label> <input type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" value="send"> </div> </form> </div> </div> </div> </div> </x-app-layout> ルートを登録 routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard'); Route::get('/articles', 'App\Http\Controllers\ArticlesController@index'); Route::get('/article/add', 'App\Http\Controllers\ArticlesController@add'); Route::post('/article/add', 'App\Http\Controllers\ArticlesController@create'); // 更新ページへのルートを登録 Route::get('/article/edit/{article}', 'App\Http\Controllers\ArticlesController@edit'); Route::post('/article/update/{article}', 'App\Http\Controllers\ArticlesController@update'); require __DIR__.'/auth.php'; これで、記事の登録に加えて更新もできるようになりました。記事を更新するためには/article/edit/1のようにarticle_idをURIに含めてリクエストしてください。ルートモデル結合を利用しているので、リクエストされたarticle_idに一致するArticleモデルが生成されサービスコンテナを通じてArticlesControllerのeditメソッドに自動的に注入されます。 作成したリソースは以下になります。 メソッド URI アクション GET /articles 一覧 GET /article/add 記事登録ページ表示 POST /article/add 記事登録 GET /article/edit/{article} 記事更新ページ表示 POST /article/edit/{article} 記事登録 作成した記事にタグを付ける機能を実装するには、下記の記事を参考に。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelで簡単なCMSを作成(認証)

Laravelで簡単なCMSを作成してみます。 環境構築とデータベースのマイグレーションは以下の記事を参考にどうぞ。 今回は認証機能を追加してみます。 スターターキットで認証機能を作成 素晴らしいことにLaravelには認証機能をサクッとつくれるようにスターターキットが用意されています。Laravel breezeを使用してシンプルな認証機能を作成します。 // パッケージをインストール composer require laravel/breeze --dev php artisan breeze:install npm install npm run dev php artisan migrate 上記のコマンドを実行するだけで、/loginにログイン画面が表示されます。ユーザーを登録するためには、/registerにアクセスします。 ログインページ ユーザー登録ページ 記事を登録する場合は、下記の記事を参考に。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelで簡単なCMSを作成(データベース作成)

Laravelで簡単なCMSを作ってみます。 環境構築は以下の記事を参考にどうぞ。 マイグレーションファイル作成 テーブル構成・定義はCakePHPのチュートリアルで紹介されているものを拝借し、3つテーブルを作成します。Laravelにはマイグレーションというデータベースの管理機能が提供されているので、これを使用します。 まずはartisanコマンドを使用してマイグレーションファイルを生成します。 php artisan make:migration create_articles_table php artisan make:migration create_tags_table php artisan make:migration create_article_tag_table テーブル定義作成 作成されたマイグレーションファイルに各テーブルの定義を加えていきます。 database/migratations/create_articles_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateArticlesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('articles', function (Blueprint $table) { $table->id(); $table->integer('user_id'); $table->string('title', 255); $table->string('slug', 191); $table->text('body'); $table->boolean('published')->default(false); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('articles'); } } database/migratations/create_tags_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTagsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tags', function (Blueprint $table) { $table->id(); $table->string('title', 191); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tags'); } } database/migratations/create_article_tag_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateArticleTagTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('article_tag', function (Blueprint $table) { $table->integer('article_id'); $table->integer('tag_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('article_tag'); } } マイグレーションファイルが作成できたらmigrateArtisanコマンドを実行してデータベースに反映させます。 php artisan migrate これだけでテーブルを作成できます。 おまけ テーブル作成後にテストデータを追加したい場合は、Laravelのシーディングを利用します。 テストデータとしてusersテーブルにuserを作成してみます。 シーダーファイルを作成 マイグレーションと同様にartisanコマンドを実行してシーダファイルを作成します。コマンド実行後database/seedersにシーダファイルが生成されます。 php artisan make:seeder UserSeeder シーダファイルが生成されたら、データ挿入処理を追加します。 database/seeders/UserSeeder.php <?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->insert([ 'name' => 'john', 'email' => 'john@gmail.com', 'password' => Hash::make('MyPassword'), ]); DB::table('users')->insert([ 'name' => 'jack', 'email' => 'jack@gmail.com', 'password' => Hash::make('MyPassword'), ]); } } シーダの呼び出し artisanコマンドを使用して個別にシーダファイルを実行することができますが、DatabaseSeederクラスのcallメソッドにシードクラスを登録することで、シーダファイルが複数になっても一括で実行できるようになります。 database/seeders/DatabaseSeeder.php <?php namespace Database\Seeders; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { // \App\Models\User::factory(10)->create(); $this->call([ UserSeeder::class, ]); } } シーダの実行 db:seed ArtisanコマンドでDatabase\Seeders\DatabaseSeederクラスを呼び出しシーディングを実行します。これによりテストデータが登録できます。 php artisan db:seed テーブルの中身を確認したいとき、vscodeの拡張機能を使用すれば簡単にテーブルデータを確認することができます。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelで簡単なCMSを作成(環境構築)

Laravelの開発環境をdockerを使ってnginx + php + sqliteの構成で作ってみます。 docker-composeで管理 ディレクトリ構成は以下です。srcディレクトリ配下にはLaravelのコードがインストールされます。 . ├── docker │ ├── nginx │ │   └── default.conf │ └── php │ ├── Dockerfile │ └── php.ini │ ├── docker-compose.yml └── src docker-composeでコンテナを管理します。 docker-compose.yml version: '3' services: nginx: image: nginx ports: - 8080:80 volumes: - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf - ./src:/var/www depends_on: - php php: build: ./docker/php volumes: - ./src:/var/www nginxの設定 default.conf server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name localhost; root /var/www/public; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { try_files $uri /index.php =404; fastcgi_pass php:9000; fastcgi_index index.php; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #fixes timeouts fastcgi_read_timeout 600; include fastcgi_params; } } phpコンテナ Dockerfile FROM php:7.3-fpm ENV COMPOSER_ALLOW_SUPERUSER 1 ENV COMPOSER_HOME /composer ENV PATH $PATH:/composer/vendor/bin #Composer install COPY --from=composer /usr/bin/composer /usr/bin/composer RUN apt-get update &&\ apt-get install -y libzip-dev &&\ docker-php-ext-configure zip --with-libzip && \ # Install the zip extension docker-php-ext-install zip && \ docker-php-ext-install pdo_mysql COPY php.ini /usr/local/etc/php/ WORKDIR /var/www php.ini [Date] date.timezone = "Asia/Tokyo" [mbstring] mbstring.internal_encoding = "UTF-8" mbstring.language = "Japanese" コンテナ起動 docker-compose.ymlファイルが置いてある場所でdocker-compose upを実行するとコンテナが起動します。バックグラウンドで起動するために-dも付けて起動させます。 docker-compose up -d Laravelインストール コンテナが起動できたらLaravelをインストールするために、phpコンテナに入ります。 # docker-compose exec php bash phpコンテナに入れたらLaravelをインストールします。 # composer create-project laravel/laravel . インストールが完了したら、http://localhost:8080にアクセスして環境が正しく構築出来ているか確認します。下の画像のように表示できていればOKです。 SQLiteの設定 laravel/database 配下に database.sqlite というファイルを作成します。次に.envファイルをsqliteを使用するために修正します。 .env DB_CONNECTION=sqlite DB_HOST=127.0.0.1 DB_PORT=3306 # DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD= これで設定は終わりです。 作成したデータベースにデータを登録する場合は、以下の記事を参考に。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む