0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Laravel] CRUD 投稿機能

Posted at

概要

よくあるCRUDの個人メモ。
投稿画面から新規にデータを追加する過程をまとめたもの。

前提条件

以下記事を参考に一覧画面を作成していること。
https://qiita.com/Hiroto10/items/4723b96b491b1ce88278

Controller

createstoreを編集することで投稿機能を実現することが可能。
createは投稿画面を表示し、storeはDBにデータを格納する役割を持つ。

storeでは入力を必須と最大255文字のチェックをかけている。
データ投稿後はトップページへリダイレクトをかける。

app/Http/Controller/TasksController.php
    public function create()
    {
        $task = new Task;

        return view('task.create', [
            'task' => $task
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'task' => 'required|max:255'
        ]);
        $task = new Task;
        $task->task = $request->task;
        $task->save();

        return redirect('/');

View

投稿画面の作成を行う。
htmlを生成するlaravelcollective/htmlを使用するためインストールする。

$ composer require laravelcollective/html:^6.0
resources/views/tasks/create.blade.php
@extends('layouts.app')

@section('content')
  @if (count($errors) > 0)
    <ul class="alert alert-danger" role="alert">
      @foreach ($errors->all() as $error)
      <li class="ml-2">{{ $error }}</li>
      @endforeach
    </ul>
  @endif

  <h1>新規タスク投稿</h1>
  <div class="row">
    <div class="col-6">
      {!! Form::model($task, ['route' => 'tasks.store']) !!}
        <div class="form-group">
          {!! Form::label('task', 'タスク') !!}
          {!! Form::text('task', null, ['class' => 'form-control']) !!}
        </div>
        {!! Form::submit('投稿', ['class' => 'btn btn-primary']) !!}
      {!! Form::close() !!}
      </div>
  </div>
@endsection

スクリーンショット 2020-10-02 0.26.13.png

一覧画面に投稿画面へ遷移するボタンを作成する。

resources/views/tasks/index.blade.php
{!! link_to_route('tasks.create', '新規タスクを投稿', [], ['class' => 'btn btn-primary']) !!}

スクリーンショット 2020-10-02 0.25.54.png

dbへの格納が成功し、一覧画面にデータが表示されたらok。


以上

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?