LoginSignup
3
2

More than 1 year has passed since last update.

laravel8 超絶簡単なCRUD処理を作る

Last updated at Posted at 2021-11-30

目的

  • laravel8にて超絶簡単なCRUD処理を含んだWebアプリを作る方法をまとめる

環境

  • ハードウェア環境
項目 情報
OS macOS Big Sur(11.6)
ハードウェア MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)
プロセッサ 2 GHz クアッドコアIntel Core i5
メモリ 32 GB 3733 MHz LPDDR4
グラフィックス Intel Iris Plus Graphics 1536 MB
  • ソフトウェア環境
項目 情報 備考
PHP バージョン 7.4.11 Homebrewを用いてこちらの方法で導入→Mac HomebrewでPHPをインストールする
Laravel バージョン 8.X commposerを用いてこちらの方法で導入→Mac Laravelの環境構築を行う
MySQLバージョン 8.0.21 for osx10.13 on x86_64 Homwbrewを用いてこちらの方法で導入→Mac HomebrewでMySQLをインストールする

概要

  • 投稿型SNSの超絶簡易版的なものを作ってWebアプリの基礎であるCRUDを学ぶ。
    • 認証機能無し
    • 画像アップロード無し
    • とにかく文字だけ投稿できるようにする。
    • ただ、依存注入、サービスクラス、リポジトリクラスなどを用いて実装を行う。
      • そのため作り的には超絶簡単ではあるが、もしかすると初心者向けじゃないかもしれません。
  • 他にももっと良い実装方法があるはずなので、参考の一部としていただきたい。
  • Macに直接laravel・MySQLローカル環境を構築してアプリを作成した。
  • 本laravel8アプリのソース

方法

  1. アプリの作成

    1. 任意のディレクトリで下記コマンドを実行してlaravel8のプロジェクトを作成する。

      $ composer create-project "laravel/laravel=8.*" laravel8_easy_crud -vvv
      
  2. MySQLにてテーブルの作成と.envの紹介

    1. MySQLにてlaravel8_easy_crudテーブルを作成する。
    2. 下記のように.envファイルに記載する。(MySQLの情報の部分は皆さんの環境に合っている情報を記載してください。)

      laravel8_easy_curd/.env
      APP_NAME=Laravel8_easy_crud
      APP_ENV=local
      APP_KEY=base64:JAeeSV6U8967eYtwwcKLjS/kXjEKBZECcfXVPLXG834=
      APP_DEBUG=true
      APP_URL=http://localhost
      
      LOG_CHANNEL=stack
      LOG_DEPRECATIONS_CHANNEL=null
      LOG_LEVEL=debug
      
      DB_CONNECTION=mysql
      DB_HOST=127.0.0.1
      DB_PORT=3306
      DB_DATABASE=laravel8_easy_crud
      DB_USERNAME=皆さんのMySQLの読み書き権限のあるユーザー名
      DB_PASSWORD=皆さんのMySQLの読み書き権限のあるユーザーのパスワード
      
      BROADCAST_DRIVER=log
      CACHE_DRIVER=file
      FILESYSTEM_DRIVER=local
      QUEUE_CONNECTION=sync
      SESSION_DRIVER=file
      SESSION_LIFETIME=120
      
      MEMCACHED_HOST=127.0.0.1
      
      REDIS_HOST=127.0.0.1
      REDIS_PASSWORD=null
      REDIS_PORT=6379
      
      MAIL_MAILER=smtp
      MAIL_HOST=mailhog
      MAIL_PORT=1025
      MAIL_USERNAME=null
      MAIL_PASSWORD=null
      MAIL_ENCRYPTION=null
      MAIL_FROM_ADDRESS=null
      MAIL_FROM_NAME="${APP_NAME}"
      
      AWS_ACCESS_KEY_ID=
      AWS_SECRET_ACCESS_KEY=
      AWS_DEFAULT_REGION=us-east-1
      AWS_BUCKET=
      AWS_USE_PATH_STYLE_ENDPOINT=false
      
      PUSHER_APP_ID=
      PUSHER_APP_KEY=
      PUSHER_APP_SECRET=
      PUSHER_APP_CLUSTER=mt1
      
      MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
      MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
      
  3. ルーティングの記入

    1. ルーティング情報を下記のように記載する。

      laravel8_easy_crud/routes/web.php
      <?php
      
      use App\Http\Controllers\ContentController;
      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::prefix('contents')->group(function() {
          Route::get('/list', [ContentController::class, 'list'])->name('contents.list');
          Route::get('/create', [ContentController::class, 'create'])->name('contents.create');
          Route::get('/update/{content_id}', [ContentController::class, 'update'])->name('contents.update');
          Route::get('/delete/{content_id}', [ContentController::class, 'delete'])->name('contents.delete');
          Route::post('/save', [ContentController::class, 'save'])->name('contents.save');
      });
      
  4. コントローラーの記載

    1. ContentController.phpを作成して下記のように記載する。

      laravel8_easy_crud/app/Http/Controllers/ContentController.php
      <?php
      
      namespace App\Http\Controllers;
      
      use App\Services\ContentService;
      use Facade\FlareClient\View;
      use Illuminate\Http\Request;
      use App\Http\Requests\ContentRequest;
      
      class ContentController extends Controller
      {
      
          public function __construct(
              ContentService $contentService
          )
          {
              $this->contentService = $contentService;
          }
      
          /**
           * 投稿一覧ページの表示
           *
           * @return view
           */
          public function list()
          {
              $content_infos = $this->contentService->getAllContentList();
              return view('contents.list', ['content_infos' => $content_infos]);
          }
      
          /**
           * 新規投稿作成
           *
           * @return view
           */
          public function create()
          {
              return view('contents.create');
          }
      
          /**
           * 投稿編集
           *
           * @param integer $content_id
           * @return view
           */
          public function update(int $content_id)
          {
              $content_info = $this->contentService->getContentInfoByContentId($content_id);
              return view('contents.update', ['content_info' => $content_info]);
          }
      
          /**
           * 投稿削除
           *
           * @param integer $content_id
           * @return view
           */
          public function delete(int $content_id)
          {
              $this->contentService->delete($content_id);
              return redirect(route('contents.list'));
          }
      
          /**
           * 新規作成・投稿編集の情報保存
           *
           * @param ContentRequest $post_data
           * @return view
           */
          public function save(ContentRequest $post_data)
          {
              $this->contentService->save($post_data);
              return redirect(route('contents.list'));
          }
      }
      
  5. サービスクラスの記載

    1. ContentService.phpを作成して下記のように記載する。

      laravel8_easy_crud/app/Services/ContentService.php
      <?php
      
      namespace App\Services;
      
      use App\Repositories\ContentRepositoryInterface as ContentRepository;
      use Illuminate\Database\Eloquent\Model;
      
      class ContentService
      {
          public function __construct(
              ContentRepository $contentRepository
          )
          {
              $this->contentRepository = $contentRepository;
          }
      
          /**
           * 投稿内容の取得
           *
           * @return Model
           */
          public function getAllContentList()
          {
              return $this->contentRepository->getAllContentList();
          }
      
          /**
           * 投稿内容IDに紐づく投稿内容の取得
           *
           * @param integer $content_id
           * @return Model
           */
          public function getContentInfoByContentId(int $content_id)
          {
              return $this->contentRepository->getContentInfoByContentId($content_id);
          }
      
          /**
           * 投稿内容の保存
           *
           * @param Request $post_data
           * @return Model
           */
          public function save($post_data)
          {
              return $this->contentRepository->save($post_data);
          }
      
          /**
           * 投稿削除
           *
           * @param integer $content_id
           * @return Model
           */
          public function delete(int $content_id)
          {
              return $this->contentRepository->delete($content_id);
          }
      }
      
  6. リポジトリクラスの記載

    1. ContentRepositoryInterface.phpを作成して下記のように記載する。

      laravel8_easy_crud/app/Repositories/ContentRepositoryInterface.php
      <?php
      
      namespace App\Repositories;
      
      use Illuminate\Database\Eloquent\Model;
      
      interface ContentRepositoryInterface
      {
          /**
           * 投稿内容の取得
           *
           * @return Model
           */
          public function getAllContentList();
      
          /**
           * 投稿内容IDに紐づく投稿内容の取得
           * 
           * @param integer $content_id
           * @return Model
           */
          public function getContentInfoByContentId(int $content_id);
      
          /**
           * 投稿内容の保存
           * 
           * @param Request $post_data
           * @return Model
           */
          public function save($post_data);
      
          /**
           * 投稿削除
           *
           * @param integer $content_id
           * @return Model
           */
          public function delete(int $content_id);
      }
      
    2. ContentRepository.phpを作成して下記のように記載する。

      laravel8_easy_crud/app/Repositories/ContentRepository.php
      <?php
      
      namespace App\Repositories;
      
      use App\Models\Content;
      use Illuminate\Database\Eloquent\Model;
      
      class ContentRepository implements ContentRepositoryInterface
      {
          public function __construct(Content $content)
          {
              $this->content = $content;   
          }
      
          /**
           * 投稿内容の取得
           *
           * @return Model
           */
          public function getAllContentList()
          {
              return $this->content
                  ->select('*')
                  ->where('deleted_flag', config('const.content.deleted_flag.false'))
                  ->get();
          }
      
          /**
           * 投稿内容IDに紐づく投稿内容の取得
           *
           * @param integer $content_id
           * @return Model
           */
          public function getContentInfoByContentId(int $content_id)
          {
              return $this->content->find($content_id);
          }
      
          /**
           * 投稿内容の保存
           *
           * @param Request $post_data
           * @return Model
           */
          public function save($post_data)
          {
              return $this->content->updateOrCreate(
                  ['id' => $post_data->id],
                  ['content' => $post_data->content],
              );
          }
      
          /**
           * 投稿削除
           *
           * @param integer $content_id
           * @return Model
           */
          public function delete(int $content_id)
          {
              $content_info = $this->content->find($content_id);
              $content_info->deleted_flag = config('const.content.deleted_flag.true');
              return $content_info->save();
          }
      }
      
    3. リポジトリクラスの登録

      1. AppServiceProvider.phpを開き下記のように記載する。

        laravel8_easy_crud/app/Providers/AppServiceProvider.php
        <?php
        
        namespace App\Providers;
        
        use Illuminate\Support\ServiceProvider;
        
        class AppServiceProvider extends ServiceProvider
        {
            /**
             * Register any application services.
             *
             * @return void
             */
            public function register()
            {
                $this->app->bind(
                    \App\Repositories\ContentRepositoryInterface::class,
                    \App\Repositories\ContentRepository::class
                );
            }
        
            /**
             * Bootstrap any application services.
             *
             * @return void
             */
            public function boot()
            {
                //
            }
        }
        
  7. ビューの記載

    1. contentsディレクトリをlaravel8_easy_crud/resources/views直下に作成する。
    2. create.blade.phpを作成して下記のように記載する。

      laravel8_easy_crud/resource/views/contents/create.blade.php
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>新規投稿</title>
      </head>
      <body>
          <header></header>
          <main>
              <h1>新規投稿</h1>
              <form action="{{ route('contents.save') }}" method="post">
                  @csrf
                  @error('content')
                      {{ $message }}
                      <br>
                  @enderror
                  <textarea name="content"  cols="30" rows="10"></textarea>
                  <input type="submit" value="投稿">
              </form>
          </main>
          <footer></footer>
      </body>
      </html>
      
    3. list.blade.phpを作成して下記のように記載する。

      laravel8_easy_crud/resource/views/contents/list.blade.php
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>投稿一覧</title>
      </head>
      <body>
          <header></header>
          <main>
              <h1>投稿内容</h1>
              <ul>
                  <li><a href="{{ route('contents.create') }}">新規投稿</a></li>
              </ul>
              @foreach ($content_infos as $content_info)
                  <div>{{ $content_info->content }}</div>
                  <div>{{ $content_info->updated_at }}</div>
                  <a href="{{ route('contents.update', ['content_id' => $content_info->id]) }}">編集</a>
                  <a href="{{ route('contents.delete', ['content_id' => $content_info->id]) }}">削除</a>
                  <br>
                  <br>
              @endforeach
          </main>
          <footer></footer>
      </body>
      </html>
      
    4. update.blade.phpを作成して下記のように記載する。

      laravel8_easy_crud/resource/views/contents/update.blade.php
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>編集</title>
      </head>
      <body>
          <header></header>
          <main>
              <h1>編集</h1>
              <form action="{{ route('contents.save') }}" method="post">
                  @csrf
                  @error('content')
                      {{ $message }}
                      <br>
                  @enderror
                  <input type="hidden" name="id" value="{{ $content_info->id }}">
                  <textarea name="content"  cols="30" rows="10">{{ $content_info->content }}</textarea>
                  <input type="submit" value="保存">
              </form>
          </main>
          <footer></footer>
      </body>
      </html>
      
  8. リクエストの記載

    1. ContentRequest.phpを作成して下記のように記載する。

      laravel8_easy_crud/app/Http/Requests/ContentRequest.php
      <?php
      
      namespace App\Http\Requests;
      
      use Illuminate\Foundation\Http\FormRequest;
      
      class ContentRequest 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
           */
          public function rules()
          {
              return [
                  'content' => ['required'],
              ];
          }
      }
      
  9. マイグレーションファイルの記載

    1. contentsテーブルを作成するためのマイグレーションファイルを用意する。
    2. 下記のように記載する。

      laravel8_easy_crud/database/migrations/YYYY_MM_DD_XXXXXX_create_contents_table.php
      <?php
      
      use Illuminate\Database\Migrations\Migration;
      use Illuminate\Database\Schema\Blueprint;
      use Illuminate\Support\Facades\Schema;
      
      class CreateContentsTable extends Migration
      {
          /**
           * Run the migrations.
           *
           * @return void
           */
          public function up()
          {
              Schema::create('contents', function (Blueprint $table) {
                  $table->id();
                  $table->text('content')->comment('投稿内容');
                  $table->unsignedTinyInteger('deleted_flag')->default(0)->comment('削除フラグ デフォルト:0 削除:1');
                  $table->timestamps();
              });
          }
      
          /**
           * Reverse the migrations.
           *
           * @return void
           */
          public function down()
          {
              Schema::dropIfExists('contents');
          }
      }
      
    3. 下記コマンドをlaravel8_easy_crudディレクトリで実行してマイグレーションを実行する。

      $ php artisan migrate
      
  10. シーダーの記載

    1. ContentSeeder.phpを作成して下記のように記載する。

      laravel8_easy_crud/database/seeders/ContentSeeder.php
      <?php
      
      namespace Database\Seeders;
      
      use Carbon\Carbon;
      use Illuminate\Database\Seeder;
      use Illuminate\Support\Facades\DB;
      
      class ContentSeeder extends Seeder
      {
          /**
           * Run the database seeds.
           *
           * @return void
           */
          public function run()
          {
              $contents = [
                  'テスト投稿_1',
                  'テスト投稿_2',
                  'テスト投稿_3',
                  'テスト投稿_4',
                  'テスト投稿_5',
                  'テスト投稿_6',
                  'テスト投稿_7',
                  'テスト投稿_8',
              ];
      
              $now = Carbon::now();
              foreach ($contents as $content) {
                  $info = [
                      'content' => $content,
                      'deleted_flag' => 0,
                      'created_at' => $now,
                      'updated_at' => $now,
                  ];
                  DB::table('contents')->insert($info);
              }
          }
      }
      
    2. DatabaseSeeder.phpを開いて下記のように記載する。

      laravel8_easy_crud/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(ContentSeeder::class);
          }
      }
      
    3. 下記コマンドをlaravel8_easy_crudディレクトリで実行してシーダーを作動させる。

      $ php artisan db:seed
      
  11. 確認

    1. $ php artisan serveコマンドにてローカルサーバーを起動する。
    2. http://127.0.0.1:8000/contents/listにアクセスする 。
    3. 下記の様に表示されることを確認する。

      投稿一覧.png

    4. 「新規投稿」 をクリックする。

      投稿一覧.png

    5. テキストエリアになにか入力して「投稿」をクリックする。

      新規投稿.png

    6. 投稿一覧ページの最下部に今投稿した内容が追加される。

      投稿一覧.png

    7. 任意の投稿の「編集」をクリックする。

      投稿一覧.png

    8. テキストエリアにすでに投稿されている内容が初期値として格納されている。何かしらの編集をして「保存」をクリックする。

      編集.png

    9. 投稿一覧ページで確認すると編集内容が反映されている。

      スクリーンショット_2021_11_30_9_37.png

    10. 「削除」をクリックすると当該の投稿が投稿一覧ページに表示されなくなる。

      スクリーンショット_2021_11_30_9_37.png

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2