LoginSignup
6
4

More than 3 years have passed since last update.

Laravel DBと連携させて一覧/追加/編集/削除ページを作成する

Last updated at Posted at 2017-12-04

前提

DBを用意し、name,mail,ageが格納されているテーブルを用意する

コード

layouts

/resources/views/layouts/helloapp.blade.php
<html>
<head>
    <title>@yield('title')</title>
    <style>
        body {font-size:16pt; color:#999; margin: 5px; }
        h1 { font-size:50pt; text-align:right; color:#f6f6f6;
            margin:-20px 0px -30px 0px; letter-spacing:-4pt; }
        ul { font-size:12pt; }
        hr { margin: 25px 100px; border-top: 1px dashed #ddd; }
        .menutitle {font-size:14pt; font-weight:bold; margin: 0px; }
        .content {margin:10px; }
        .footer { text-align:right; font-size:10pt; margin:10px;
            border-bottom:solid 1px #ccc; color:#ccc; }
        th {
            background-color:#999;
            color:#FFF;
            padding:5px 10px;
        }
        td {
            border:solid 1px #aaa;
            color:#999;
            padding:5px 10px;
        }
    </style>
</head>
<body>
<h1>@yield('title')</h1>
@section('menubar')
    <ul>
        <p class="menutitle">※メニュー</p>
        <li>@show</li>
    </ul>
    <hr size="1">
    <div class="content">
        @yield('content')
    </div>
    <div class="footer">
        @yield('footer')
    </div>
</body>
</html>

view

index.blade.php

検索結果を表示させるためのコード
foreachで検索結果分、リクエストされたID分表示するような仕組みになっている

/resources/views/hello/index.blade.php
@extends('layouts.helloapp')

@section('title', 'Index')

@section('menubar')
    @parent
    インデックスページ
@endsection

@section('content')
    <table>
        <tr><th>Name</th><th>Mail</th><th>Age</th></tr>
        @foreach ($items as $item)
            <tr>
                <td>{{$item->name}}</td>
                <td>{{$item->mail}}</td>
                <td>{{$item->age}}</td>
            </tr>
        @endforeach
    </table>
@endsection

@section('footer')
    copyright 2017 atsumi.
@endsection

add.blade.php(追加ページ)

name,mail,ageを追加するコード

@extends('layouts.helloapp')

@section('title', 'Add')

@section('menubar')
    @parent
    新規作成ページ
@endsection

@section('content')
    <table>
        <form action="add" method="post">
            {{csrf_field()}}
            <tr>
                <th>name:</th>
                <td><input type="text" name="name"></td>
            </tr>
            <tr>
                <th>mail:</th>
                <td><input type="text" name="mail"></td>
            </tr>
            <tr>
                <th>age:</th>
                <td><input type="text" name="age"></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="submit" value="send"></td>
            </tr>
        </form>
    </table>
@endsection

@section('footer')
    copyright 2017 tuyano.
@endsection

del.blade.php(削除ページ)

del.blade.php
@extends('layouts.helloapp')

@section('title', 'Delete')

@section('menubar')
    @parent
    削除ページ
@endsection

@section('content')
    <table>
        <form action="del" method="post">
            {{csrf_field()}}
            <input type="hidden" name="id" value="{{$form->id}}">
            <tr>
                <th>name:</th>
                <td><input type="text" name="name" value="{{$form->name}}"></td>
            </tr>
            <tr>
                <th>mail:</th>
                <td><input type="text" name="mail" value="{{$form->mail}}"></td>
            </tr>
            <tr>
                <th>age:</th>
                <td><input type="text" name="age" value="{{$form->age}}"></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="submit" value="send"></td>
            </tr>
        </form>
    </table>
@endsection

@section('footer')
    copyright 2017 tuyano.
@endsection

edit.blade.php (編集ページ)

edit.blade.php
@extends('layouts.helloapp')

@section('title', 'edit')

@section('menubar')
    @parent
    更新ページ
@endsection

@section('content')
    <table>
        <form action="edit" method="post">
            {{csrf_field()}}
            <input type="hidden" name="id" value="{{$form->id}}">
            <tr>
                <th>name:</th>
                <td><input type="text" name="name" value="{{$form->name}}"></td>
            </tr>
            <tr>
                <th>mail:</th>
                <td><input type="text" name="mail" value="{{$form->mail}}"></td>
            </tr>
            <tr>
                <th>age:</th>
                <td><input type="text" name="age" value="{{$form->age}}"></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="submit" value="send"></td>
            </tr>
        </form>
    </table>
@endsection

@section('footer')
    copyright 2017 tuyano.
@endsection

controller

index,addアクションにそれぞれSQL文を記述する

index→IDパラメータが付与されていれば、そのIDの名前、メールアドレス、年齢を表示
add →名前、メールアドレス、年齢を追加する

app/Http/Controllers/HelloController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\HelloRequest;
use Validator;


class HelloController extends Controller
{
    public function index(Request $request)
    {
       if(isset($request->id)) {
            $param = ['id'=>$request->id];
            $items = DB::select('SELECT * FROM people where id = :id',$param);
        } else {
            $items = DB::select('SELECT * FROM people');
        }
        return view('hello.index',['items'=>$items]);
    }

    public function post(Request $request)
    {
        $validate_rule = [
            'msg' => 'required',
        ];
        $this->validate($request, $validate_rule);
        $msg = $request->msg;
        $response = new Response(view('hello.index', ['msg'=>
            '「' . $msg . '」をクッキーに保存しました。']));
        $response->cookie('msg', $msg, 100);
        return  $response;
    }

    public function add(Request $request)
    {
        return view('hello.add');
    }

    public function create(Request $request)
    {
        $param = [
            'name' => $request->name,
            'mail' => $request->mail,
            'age' => $request->age,
        ];
        DB::insert('INSERT INTO people (name,mail,age) VALUES (:name,:mail,:age)',$param);
        return redirect('/hello');
    }

    public function edit(Request $request)
    {
        $param = ['id' => $request->id];
        $item = DB::select('SELECT * FROM people where id = :id',$param);
        return view('hello.edit',['form'=>$item[0]]);
    }

    public function update(Request $request)
    {
        $param = [
            'id' => $request->id,
            'name' => $request->name,
            'mail' => $request->mail,
            'age' => $request->age,
        ];
        DB::update('UPDATE people SET name = :name,mail = :mail,age = :age where id = :id',$param);
        return redirect('hello');
    }

    public function del(Request $request)
    {
        $param = [
            'id' => $request->id
        ];
        $item = DB::select('SELECT * FROM people WHERE id = :id',$param);
        return view('hello.del',['form'=>$item[0]]);
    }

    public function remove(Request $request)
    {
        $param = ['id'=>$request->id];
        DB::delete('DELETE FROM people where id = :id',$param);
        return redirect('hello');
    }
}

web.php

/routes/web.php
<?php

/*
|--------------------------------------------------------------------------
| 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!
|
*/

//HelloController.php と連携
Route::get('hello','HelloController@index')->middleware('hello');
Route::post('hello','HelloController@post');
Route::get('hello/add','HelloController@add');
Route::post('hello/add','HelloController@create');
Route::get('hello/edit','HelloController@edit');
Route::post('hello/edit','HelloController@update');
Route::get('hello/del','HelloController@del');
Route::post('hello/del','HelloController@remove');
6
4
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
6
4