LoginSignup
2
1

More than 5 years have passed since last update.

Laravel5.5 データ一覧表示と登録まで

Last updated at Posted at 2018-07-22

eloquentで実装してみました。

\resources\views\article\index.blade.php
<form method="POST" action="/article">
    {{ csrf_field() }} <!-- セキュリティ上必要 -->
    title<input type="text" name="title"><br><br>
    body<input type="text" name="body">
    <input type="submit" value="投稿">
</form>
<br><br>
<!-- 一覧 -->
@foreach($articles as $article)
    {{$article->title}}<br>
    {{$article->body}}<br><br>
@endforeach
\app\Http\Controllers\ArticleController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Article;

class ArticleController extends Controller
{
    public function index()
    {
        // データベースから全データを取得
        $article = Article::all();
        // viewにデータを渡す
        return view('article.index', ['articles' => $article]);
    }

    public function post (Request $request)
    {
        // インスタンスを作成
        $article = new Article;
        // 格納するデータを代入
        $article->user_id = '1';

        // post送信されたデータを代入
        $article->title = $request->input('title');
        $article->body = $request->input('body');
        // データを保存
        $article->save();

        // 終わったらリダイレクトする
        return redirect()->to('/article');

    }
}
2
1
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
2
1