トッカンソフトウェア

Laravel コントローラ、ビュー

コントローラを作成してみます。前回の続きからやります。

ビューの作成

コマンドプロンプトでphp artisan make:view を実行するとビューが作成されます。

php artisan make:view test

上記、コマンドを実行すると、test.blade.phpが作成されます。

resources\views\test.blade.php

<div>
	<!-- Walk as if you are kissing the Earth with your feet. - Thich Nhat Hanh -->
</div>
			
以下のように変更します。

<div>
    Hello View
</div>


コントローラの作成

コマンドプロンプトでphp artisan make:controller を実行するとコントローラが作成されます。

php artisan make:controller TestController

上記、コマンドを実行すると、TestController.phpが作成されます。

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
	//
}
		
以下のように変更します。

<?php

namespace App\Http\Controllers;

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

class TestController extends Controller
{
    public function show(): View
    {
        return view('test');
    }
}


ルーティングの設定

/test が指定されたときにTestControllerのshowメソッドが呼ばれるように設定します。

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


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

php artisan serve --port=8080

以下にアクセスします。

http://localhost:8080/test

Hello Viewが表示されます。


ページのトップへ戻る