トッカンソフトウェア

Laravel コントローラ、ビュー2

検索画面から一覧画面の画面遷移っぽいことをやっています。環境構築はこちらを参照して下さい。
コントローラ、ビューの作成は前回を参照して下さい。

コントローラの修正

app\Http\Controllers\TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;

class TestController extends Controller
{
    // 初期表示
    public function show(): View
    {
        return view('test', ['id' => '']);
    }

    //検索して一覧画面を表示
    public function post(Request $request): View
    {
        $id = $request->input('id');

        if (trim($id) == "") {
            return view('test', ['id' => '', 'msg' => '未入力']);
        }

        $ary = [
            ['aaa' => 'hello', 'bbb' => 'world'],
            ['aaa' => 'aaa1', 'bbb' => 'bbb1'],
        ];

        return view('test_list', ['ary' =>  $ary]);
    }

    //一覧画面から画面遷移
    public function get($id): View
    {
        return view('test', ['id' => $id]);
    }
}

POST元の画面からデータを取得する場合は、$request->input('XXX');を使用します。
GETでURLからデータを取得する場合はweb.phpでURLのデータ箇所を指定して、データは引数から取得します。

ビューの修正

Hello Viewを表示した画面は、検索画面(詳細画面も兼ねる)っぽい画面に変更します。

resources\views\test.blade.php

<form method="POST" action="/test">
    @csrf
    <input type="text" name="id" value="{{$id}}" />
    <input type="submit" />

    @isset($msg)
    <p>{{$msg}}</p>
    @endisset
</form>
@csrfは不正アクセスを防ぐためLaravelが用意してくれている機能になり、必ず指定する必要があります。

新規ビューの作成

新たに一覧画面にあたるビューを作成します。

resources\views\test_list.blade.php

<table>
    @foreach ($ary as $map)
    <tr>
        <td><a href="{{ route('test.get',[ $map['aaa']]) }}">{{ $map['aaa'] }}</td>
        <td>{{ $map['bbb'] }}</td>
    </tr>
    @endforeach
</table>

ルーティングの設定

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/hello', function () {
    return 'hello world!!';
});

Route::get('/test', [TestController::class, 'show']);

Route::post('/test', [TestController::class, 'post']);

Route::get('/test/{id}', [TestController::class, 'get'])->name('test.get');


テスト用サーバを起動します。

php artisan serve --port=8080

以下にアクセスします。

http://localhost:8080/test

何か入力して送信ボタンを押下すると一覧画面に遷移します。


リンクをクリックすると詳細画面に遷移します。


ページのトップへ戻る