Laravelでブログサイト制作
https://scrapbox.io/files/62bb46b03b1f9d001d318c41.png
作成者
タグ付け
参考サイト
以下のYoutubeを参考に制作しました
https://youtube.com/playlist?list=PLCyDm9NTxdhLnA4tH5ToQR1K1LcWIAdOa
Laravelとは
Webアプリケーションフレームワーク
php言語
MVC モデル
開発環境
使用PC:M1 macbook air
OS:11.6
開発ツール:MAMP
開発構築
MAMPのインストール
URL👇
Composerのインストール
Composer:PHPのパッケージ管理ツール
Composerをインストール
curl -sS https://getcomposer.org/installer | php
ディレクトリの移動
sudo mv composer.phar /usr/local/bin/composer
Composerのバージョン確認
composer -V
プロジェクトの作成
blogプロジェクトの作成
ディレクトリの移動
cd /Applications/MAMP/htdocs/
blogプロジェクトの作成(composer create-project laravel/laravel --prefer-dist プロジェクト名)
composer create-project laravel/laravel --prefer-dist blog
プロジェクトのディレクトリに移動(以降このディレクトリで作業する)
cd blog
書き込み権限
chmod -R 777 storage
chmod -R 777 bootstrap/cache
MAMPの設定
MAMPアプリを立ち上げる
Preferenceをクリック
Serverタブをクリック
Document rootを以下になるように設定
Application/MAMP/htdocs/blog(プロジェクト名)/public
https://scrapbox.io/files/62b75942673a20001de508da.png
OKを押して,Startを押すとローカルサーバが立つ
DBの設定
phpMyAdminの設定
ToolsからphpMyAdminをクリック
https://scrapbox.io/files/62b75b34f7a990001d85d3f4.png
(1)新規作成タブをクリック
(2)データベース名をblogに設定(今回文字コードはutf8mb4_unicode_ci)
(3)データベースができたか確認
https://scrapbox.io/files/62b75c208afab3001dd885c0.png
環境変数の設定
https://scrapbox.io/files/62b75d36b16d30001d2e1a8d.png
.envファイルにアクセスしDBを以下のように記述する
code:.env一部
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=root
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
文字コードが不対応時の設定
app/Providers/AppServiceProvider.phpにアクセス
使用するライブラリの追加
use Illuminate\Support\Facades\Schema;
bootメソッドに以下を追加
Schema::defaultStringLength(191);
今回の実装
code:AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
Schema::defaultStringLength(191);
}
}
configの設定
code:config/app.php
<?php
use Illuminate\Support\Facades\Facade;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'Asia/Tokyo', //タイムゾーン
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'ja', //ロケーション
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'ja',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'ja_JP', //fakerの日本語化
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'ExampleClass' => App\Example\ExampleClass::class,
])->toArray(),
];
DBマイグレーション
マイグレーション
SQLを直接使わないデータベース管理システム
テーブル作成の流れ
マイグレーションファイルを作成
ファイルにテーブル定義を書く
マイグレーションを実行し,DBに反映
マイグレーション生成
場所:database/migrations
ファイル名:2014_10_12_000000_create_users_table.php
ファイル名規則:生成時間(2014_10_12_000000)_アクション名(create)_テーブル名(users)
ファイル生成コマンド(php artisan make:migration create_テーブル名_table)
ディレクトリの移動
cd /Applications/MAMP/htdocs/blog
ファイル生成
php artisan make:migration create_blogs_table
マイグレーションファイル(2022_00_00_000000_create_blogs_table.php)にカラムを追加
追加カラム:title(ブログタイトル),content(ブログ内容)
今回の実装
code:マイグレーションファイル.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('blogs')){ //blogsテーブルが無ければテーブル追加
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->string('title', 100);//100文字以内のタイトルカラム追加
$table->text('content');//ブログ内容カラム追加
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('blogs');
}
};
実行コマンド
php artisan migrate
マイグレーションの詳細
upとdownメソッド
upが実行(作成)
downがもとに戻す(削除)
Schemaファサードを使用
Schema::create
カラムの作成はBlueprintオブジェクトのtableメソッドを使う
$table->string('name') // 名前カラムを作成
MVCとEloquent ORM
MVC
Model,View,Contorollerに分けてWebアプリを実装する手法
Model
システムの中でDB処理やビジネスロジックを担当する
View
表示や入出力といった処理
サイトの見た目を担当
Contoroller
ユーザーのアクセスや入力に基づき,ModelとViewを制御する
Eloquent ORM
Laravel で提供されているデータ操作のための機能
「Model(DB処理,ロジック)」 と「DB」を対応づける
ORM
Object Relational Mappingの略
プログラミング技法
データベースから取得したデータをオブジェクトして扱える
Eloquentモデルの作成
作成コマンド
php artisan make:model モデル名
モデル名はテーブル名の単数形にする
今回の実行コマンド
php artisan make:model Models/Blog
ModelとDBの対応付け,属性保護
今回の実装
code:app/Models/Blog.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
use HasFactory;
// テーブル名
protected $table = 'blogs';
// 可変項目
protected $fillable =
[
'title',
'content'
];
}
fillableプロパティ
ホワイトリスト
$fillableに指定したカラムのみ、create()やfill()、update()で値が代入される
複数代入(複数のカラムにデータを入れる)できる
guardedプロパティ
ブラックリスト
$guardedに指定したカラムのみ、create()やfill(),update()で値が代入されない
複数代入(複数のカラムにデータを入れる)できない
ルーティング
ルーティング
ブラウザから任意のURLにアクセスがあった場合、 どのController処理を動かすのかを定義する
routes/web.php ファイルに処理を記述する
HTTPメソッドも定義できる (GET、 POST, PUT, DELETE)
記述例
完全修飾名での記述
Route::get(’blogs’, ‘App\Http\Controllers\BlogController@showlist’)->name('blogs’);
get:httpメソッド,blogs:任意のURL,BlogController:作ったControllerを指定
@showlist:Contorollerのメソッド名,->name('blogs’):ルートの名前
App\Http\Controllers\BlogController@showlistは完全修飾名で記述
useでのインポート
code:web.php
use App\Http\Controllers\BlogController;
今回の実装
code: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('/', 'App\Http\Controllers\BlogController@showList')->name('blogs');
// ブログ登録画面を表示
Route::get('/blog/create', 'App\Http\Controllers\BlogController@showCreate')->name('create');
// ブログ登録
Route::post('/blog/store', 'App\Http\Controllers\BlogController@exeStore')->name('store');
// ブログ詳細画面を表示
Route::get('/blog/{id}', 'App\Http\Controllers\BlogController@showDetail')->name('show');
// ブログ編集画面を表示
Route::get('/blog/edit/{id}', 'App\Http\Controllers\BlogController@showEdit')->name('edit');
Route::post('/blog/update', 'App\Http\Controllers\BlogController@exeUpdate')->name('update');
// ブログ削除
Route::post('/blog/delete/{id}', 'App\Http\Controllers\BlogController@exeDelete')->name('delete');
コントローラ
コントローラ
route で定義されたHTTPリクエスト (URL) の処理を書く
Laravelの既存のコントローラクラスを拡張して作られる
例えば、 ブログの処理をするコントローラはBlog Controllerでまとめる
コントローラの作成
ブログコントローラを作る
実行コマンド
php artisan make:controller BlogController
コントローラの呼び出し,流れ
ルート
場所:routes/wep.php
表記例
Route::get('blogs', 'BlogController@showList')
コントローラ
場所:controller/BlogController.php
表記例
public function showList()
※コントローラーはスリム(コードを少なく)にするのが良い
今回の実装
code:app/Http/Controllers/BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog;
use App\Http\Requests\BlogRequest;
class BlogController extends Controller
{
/**
* ブログ一覧を表示する
*
* @return view
*/
public function showList()
{
// Blogテーブルの中身を取り出す
$blogs = Blog::all();
// blog/list.blade.phpにblogsをキーとして$blogsを渡す
}
/**
* ブログ詳細を表示する
* @param int $id
* @return view
*/
public function showDetail($id)
{
// Blogテーブルのidに書かれた記事を取り出す
$blog = Blog::find($id);
// 記事が無いとき
if (is_null($blog)) {
\Session::flash('err_msg', 'データがありません。');
return redirect(route('blogs'));
}
// blog/detail.blade.phpにblogをキーとして$blogを渡す
}
/**
* ブログ登録画面を表示する
*
* @return view
*/
public function showCreate()
{
// blog/form.blade.phpへ
return view('blog.form');
}
/**
* ブログを登録する
*
* @return view
*/
public function exeStore(BlogRequest $request)
{
// ブログのデータを受け取る
$inputs = $request->all();
// トランザクション開始
\DB::beginTransaction();
try {// うまくいけば
// ブログを登録
Blog::create($inputs);
// トランザクションのコミット
\DB::commit();
} catch(\Throwable $e) {// うまくいかなければ
// トランザクションのロールバック
\DB::rollback();
// 500エラーページに飛ばす
abort(500);
}
\Session::flash('err_msg', 'ブログを登録しました');
// ブロク一覧へリダイレクト
return redirect(route('blogs'));
}
/**
* ブログ編集フォームを表示する
* @param int $id
* @return view
*/
public function showEdit($id)
{
$blog = Blog::find($id);
if (is_null($blog)) {
\Session::flash('err_msg', 'データがありません。');
return redirect(route('blogs'));
}
}
/**
* ブログを更新する
*
* @return view
*/
public function exeUpdate(BlogRequest $request)
{
// ブログのデータを受け取る
$inputs = $request->all();
\DB::beginTransaction();
try {
// ブログを更新
$blog = Blog::find($inputs'id'); $blog->fill([
]);
$blog->save();
\DB::commit();
} catch(\Throwable $e) {
\DB::rollback();
abort(500);
}
\Session::flash('err_msg', 'ブログを更新しました');
return redirect(route('blogs'));
}
/**
* ブログ削除
* @param int $id
* @return view
*/
public function exeDelete($id)
{
if (empty($id)) {
\Session::flash('err_msg', 'データがありません。');
return redirect(route('blogs'));
}
try {
// ブログを削除
Blog::destroy($id);
} catch(\Throwable $e) {
abort(500);
}
\Session::flash('err_msg', '削除しました。');
return redirect(route('blogs'));
}
}
view
view
resources/viewsのなかのbladeを返す
Bladeテンプレート
Laravelのテンプレートエンジン
※PHPにはsmartyというテンプレートエンジンもある
HTMLを書くイメージ
BladeはPHPを直接記述できる
Bladeはテンプレートの継承やデータの受け渡しができる
Bootstrapの導入
コマンド
composer require laravel/ui
php artisan ui bootstrap
Viewの継承
親Viewですべきこと
@yieldで各子ビュー固有のパーツをどこで反映させたいかを記述する。
@yield('section名')
@includeでbladeファイルを読み込む。
@include('bladeを指定')
子Viewですべきこと
@extendsで今から親ビューを継承する、と宣言する。
@extends('bladeを指定')
@sectionで自分固有のパーツを定義する。
@section('セクションの名前')
bladeの作成
今回の実装
ヘッダ
code:resouces/views/header.blade.php
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{{ route('blogs') }}">ブログ</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="{{ route('blogs') }}">ブログ一覧 <span class="sr-only"></span></a>
<a class="nav-item nav-link" href="{{ route('create') }}">ブログ投稿</a>
</div>
</div>
</nav>
フッタ
code:resouces/views/footer.blade.php
<div class="container text-center">
<span class="text-light">blog</span>
</div>
レイアウト
code:resouces/views/layout.blade.php
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}"> <!-- csrf対策 -->
<title>@yield('title')</title>
<link rel="stylesheet" href="/css/app.css">
<script src="/js/app.js" defer></script>
</head>
<body>
<header>
@include('header') <!-- ヘッダ共通化 -->
</header>
<br>
<div class="container"> <!-- コンテンツパーツ -->
@yield('content')
</div>
<footer class="footer bg-dark fixed-bottom">
@include('footer') <!-- フッタ共通化 -->
</footer>
</body>
</html>
ブログリスト
code:resouces/views/blog/list.blade.php
@extends('layout') <!-- layout.bladeを継承 -->
@section('title', 'ブログ一覧') <!-- セクションで引数の指定も可能 -->
@section('content') <!-- コンテンツセクション -->
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2>ブログ記事一覧</h2>
<table class="table table-striped">
<tr>
<th>記事番号</th>
<th>日付</th>
<th>タイトル</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>2112/09/03</td>
<td>テスト</td>
<td></td>
</tr>
</table>
</div>
</div>
@endsection
ブログ表示の処理の流れ
EloquentモデルでDBからブログデータを取り出す
Eloquentモデルのメソッドを使ってデータを取得
今回はallメソッドを使用
Controllerでモデルクラスを呼び出してVIewにデータを渡す
Blade(view)でブログデータを一覧表示する
ブログ投稿
code:resouces/views/blog/form.blade.php
@extends('layout')
@section('title', 'ブログ投稿')
@section('content')
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2>ブログ投稿フォーム</h2>
<form method="POST" action="{{ route('store') }}" onSubmit="return checkSubmit()">
@csrf
<div class="form-group">
<label for="title">
タイトル
</label>
<input
id="title"
name="title"
class="form-control"
value="{{ old('title') }}"
type="text"
@if ($errors->has('title'))
<div class="text-danger">
{{ $errors->first('title') }}
</div>
@endif
</div>
<div class="form-group">
<label for="content">
本文
</label>
<textarea
id="content"
name="content"
class="form-control"
rows="4"
{{ old('content') }}</textarea>
@if ($errors->has('content'))
<div class="text-danger">
{{ $errors->first('content') }}
</div>
@endif
</div>
<div class="mt-5">
<a class="btn btn-secondary" href="{{ route('blogs') }}">
キャンセル
</a>
<button type="submit" class="btn btn-primary">
投稿する
</button>
</div>
</form>
</div>
</div>
<script>
function checkSubmit(){
if(window.confirm('送信してよろしいですか?')){
return true;
} else {
return false;
}
}
</script>
@endsection
ブログ登録の流れ
フォームからデータを飛ばす(CSRF保護必須)
routeで受け取りControllerへ
フォームリクエストでバリデート
Modelでデータを登録(トランザクション処理を入れる)
エラー処理(DBエラーの対処(try-catch))
ブログ詳細
code:resouces/views/blog/detail.blade.php
@extends('layout') <!-- layout.bladeを継承 -->
@section('title', 'ブログ詳細') <!-- セクションで引数の指定も可能 -->
@section('content') <!-- コンテンツセクション -->
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2>{{ $blog->title }}</h2>
<span>作成日:{{ $blog->created_at }}</span>
<span>更新日:{{ $blog->updated_at }}</span>
<p>{{ $blog->content }}</p>
</div>
</div>
@endsection
ブログ詳細表示の処理の流れ
詳細表示したいブログのIDでリンクを作って飛ばす
routeでIDを受け取り Controllerへ渡す
Modelで該当IDデータを取り出す
Viewで表示する
ブログ編集フォーム
code:resouces/views/blog/edit.blade.php
@extends('layout')
@section('title', 'ブログ編集')
@section('content')
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2>ブログ編集フォーム</h2>
<form method="POST" action="{{ route('update') }}" onSubmit="return checkSubmit()">
@csrf
<input type="hidden" name="id" value="{{ $blog->id }}">
<div class="form-group">
<label for="title">
タイトル
</label>
<input
id="title"
name="title"
class="form-control"
value="{{ $blog->title }}"
type="text"
@if ($errors->has('title'))
<div class="text-danger">
{{ $errors->first('title') }}
</div>
@endif
</div>
<div class="form-group">
<label for="content">
本文
</label>
<textarea
id="content"
name="content"
class="form-control"
rows="4"
{{ $blog->content }}</textarea>
@if ($errors->has('content'))
<div class="text-danger">
{{ $errors->first('content') }}
</div>
@endif
</div>
<div class="mt-5">
<a class="btn btn-secondary" href="{{ route('blogs') }}">
キャンセル
</a>
<button type="submit" class="btn btn-primary">
更新する
</button>
</div>
</form>
</div>
</div>
<script>
function checkSubmit(){
if(window.confirm('更新してよろしいですか?')){
return true;
} else {
return false;
}
}
</script>
@endsection
ブログ編集の流れ
ブログ一覧からIDで編集フォームへ
route作成
編集フォームからPOSTで送る
フォームリクエストでバリデート
Contoroller&Modelでデータ登録
エラー処理
バリデーション
バリデーション
入力されたデータが正しいかどうかをチェックする
必須チェックや文字数チェックなど
Laravelフォームリクエスト
Illuminate\Http\Requestsにある
validateメソッド
バリデーションのルールを作成でき、失敗したらエラー ($errors) を返せる
今回の実装
code:app/Http/Requests/BlogRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BlogRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'title' => 'required | max:100',
'content' => 'required'
];
}
}
テストデータ
seeder
seederはLaravelのクラスの一つ
テストデータを簡単にデータベースに設定できる
Factoryによってランダムデータを与える
seederの使い方
生成・実行
php artisan make:seeder ファイル名
php artisan db:seed
seederファイルを編集
runメソッドに設定を記述
データ作成の処理を書いていく
DatabaseSeeder.phpに登録
作ったシーダーをこのファイルに登録することで呼び出せる
factory
Eloquentモデルを使ってテストデータを作るときの機能
自動でデフォルト値を設定できる
複数のデータを一括で作れる
Factoryの使い方
生成
php artisan make:factory ファイル名
php artisan db:seed
Faker PHPライブラリ
ダミーデータを生成するphpライブラリ
今回の実装
php artisan make:seeder BlogsTableSeeder
code:database/seeds/BlogTableSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Blog;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class BlogsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Blog::factory()->count(15)->create();
}
}
php artisan make:factory BlogFactory
code:database/seeds/BlogFactory.php
<?php
namespace Database\Factories;
use App\Models\Blog;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model>
*/
class BlogFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
protected $blog = Blog::class;
public function definition()
{
return [
'title' => $this->faker->word(),
'content' => $this->faker->realText()
];
}
}
composer dump-autoload
php artisan config:clear
https://scrapbox.io/files/629087f925856c001dd1896d.png
seederで生成したテストデータ