laravelでの表示までの実装方法
私は、今回PHP言語、フレームワークにlareavelを使いエビングハウスの忘却曲線を元に学習を効率的に行うことができるアプリを作成していきます。
1.目的
作成したページを表示できるようにしていきます。
2.使うもの
なし
3.方法
①次にルーティングを定義していきます。/routes/web.phpファイルを以下のように編集していきます。
<?php
use Illuminate\Support\Facades\Route;
//以下追加 httpメソッドを使えるようにしている。
use Illuminate\Http\Request;
//ここまで
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::get('/', function () {
return view('welcome');
});
//以下追加
Route::resource('/item','ItemsController',['only' =>['index','create','store']]);
//ここまで
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
②laravel8から仕様変更されコントローラーが存在しないと出るためApp/Http/Providers/RouteServiceProvider.phpを以下のように変更しコントローラーを呼び出せるようにします。
//以下追記
protected $namespace = 'App\Http\Controllers';
//ここまで
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
ここでは、webミドルウェアとApp\Http\Controllersの名前空間を使用して、routes/web.phpにルートをロードするよう指示しています。
③terminalにて以下のコマンドを実行しコントローラーとアクションを作成させます。
% php artisan make:controller ItemsController --resource
④app/resources/views以下にitemsフォルダを作成し、その中にindex.blade.phpファイルを作成します。
⑤index.blade.phpファイル内を以下のように編集します。
@extends('layouts.app')
@section('content')
<h1>hello World</h1>
@endsection
⑥/routes/web.phpファイルを以下のように変更しホーム画面を上記で作成したviewにします。
Route::get('/', function () {
//以下変更
return view('items/index');
//ここまで
});
⑦最後にterminalで以下のコマンドを実行しサーバーを起動させます。
% php artisan serve
4.まとめ
http://localhost:8000/を開いて以下のように表示されたらOK!!です。
ありがとうございました!!
この記事が気に入ったらサポートをしてみませんか?