LoginSignup
0
0

More than 1 year has passed since last update.

Chapter5 DBクラスの利用(5-2)

Last updated at Posted at 2022-07-02

DBクラスとは?

Laravelに用意されている、
最もシンプルなデータベースアクセス機能は「DB」クラスです。

中でも、最もシンプルなのは、SQLのクエリを直接実行するメソッドです。

DBクラスを使用

コントローラの修正

HelloController.php
use Illuminate\Support\Facades\DB;

class HelloController extends Controller
{

    public function index(Request $request) {

        $items = DB::select('select * from people');

        return view('hello.index',['items' => $items]);

    }

}

テンプレートの修正

index.php
@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

上記の記述をすることで、
「people」テーブルから参照して、レコードを表示することができる。

スクリーンショット 2022-07-03 1.41.44.png

調べている間に、参考になりなる記事があったので記載。

DB::selectの利用

HelloController.php
$items = DB::select('select * from people');

上記がデータベースからレコードを取り出すための処理の記述。
DB::selectは、DBクラスにある静的メソッドで、以下のように呼び出す。

sample.php
$変数 = DB::select('**実行するSQL文**);

パラメータ結合の利用

パラメータ結合 とは、
文字列とパラメータ配列を組み合わせてSQL文を作成する方法です。

HelloController.php
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]);
}
HelloController.php
$param = ['id' => $request->id];

['id' => パラメータ]という配列を用意します。

HelloController.php
$items = DB::select('select * from people where id = :id', $param);

where id = :id:idはパラメータの値をはめ込むプレースホルダを指します。

DB::insertによるレコード作成

レコード追加用のテンプレートページを作成。

add.php
@extends('layouts.helloapp')

@section('title','Add')

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

@section('content')

    <form action="/hello/add" method="post">

        <table>
            @csrf
            <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" name="send"></td></tr>

        </table>

    </form>

@endsection

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

コントローラへレコード追加処理の追加

HelloController.php
class HelloController extends Controller
{

    public function index(Request $request) {

        $items = DB::select('select * from people');

        return view('hello.index',['items' => $items]);

    }

    public function post(Request $request) {

        $items = DB::select('select * from people');

        return view('hello.index',['items' => $items]);

    }

    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');

    }

}

ルート情報の追加

addページにルーティングするように、「web.php」に登録する。

web.php
Route::get('hello/add','App\Http\Controllers\HelloController@add');
Route::post('hello/add','App\Http\Controllers\HelloController@create');

DB::updateによる更新

更新用テンプレートページの作成

eidt.php
@extends('layouts.helloapp')

@section('title','Edit')

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

@section('content')

    <form action="/hello/edit" method="post">

        <table>
            @csrf
            <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" name="send"></td></tr>

        </table>

    </form>

@endsection

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

フォームのvalue$formの値を設定することで、
$formに更新するレコードの値を設定しておけばその値が表示されるようになります。
またレコードを更新する際に、どのレコードを更新するのか判断するための、
<input type="hidden" name="id" value="{{$form->id}}">
$formに「id」を持たせ、どのレコードを更新するのかを判断できるようにしています。

更新処理の追加

HelloController.php
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');

    }

ルーティング情報の登録

web.php
Route::get('hello/edit','App\Http\Controllers\HelloController@edit');
Route::post('hello/edit','App\Http\Controllers\HelloController@update');

DB::deleteによる削除

削除用のテンプレートページを作成。

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

@section('title','Edit')

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

@section('content')

    <form action="/hello/del" method="post">

        <table>
            @csrf
            <input type="hidden" name="id" value="{{$form->id}}">
            <tr><th>name: </th><td>{{$form->name}}</td></tr>
            <tr><th>mail: </th><td>{{$form->mail}}</td></tr>
            <tr><th>age: </th><td>{{$form->age}}</td></tr>
            <tr><th></th><td><input type="submit" name="send"></td></tr>

        </table>

    </form>

@endsection

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

削除処理をコントローラに追加する

HelloController.php
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
Route::get('hello/del','App\Http\Controllers\HelloController@del');
Route::post('hello/del','App\Http\Controllers\HelloController@remove');

これで、でーたベース操作の基本である「CRUD」の実装はできましたが、
コントローラにSQLクエリ文をそのまま記述しただけのやり方であまりスマートではない。

次回、クエリビルダを利用するとよりPHPらしい記述でDB操作ができる。

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