[Laravel] ディレクトリ構造

ルーティング(URLの定義)

作業ファイル:routes/web.php

Route::get('/animal/{species}/', function($species) {
    return view('species', ['species'=>$species]);
});

この例では、https://<サイト名>/animal/dog/などでアクセスできます。

ビュー(HTML本文)

作業ファイル:resources/views/<viewに渡した名前>.blade.php(例:species.blade.php)

  • resources/views/の下にフォルダーを作成した場合(例:/animal/species.blade.php)
    web.phpファイルでは、return view('animal.species');のようにピリオドで区切ります。
  • web.phpから受け取った変数は、{{ $variable }}(Bladeテンプレートエンジン)の形式で記述します。

if文(Bladeの記法)

@if ($species === 'dog')
<p>犬のページへようこそ</p>
@endif

その他の記法:Laravel 7.x Bladeテンプレート

コントローラー

作業ファイル:app/Http/Controllers/<ファイル名>.php(例:MathController.php)

以下のコマンドで空のコントローラーファイルを作成します。

php artisan make:controller MathController

クラス内にメソッドを記述し、適宜use文を追加します。

例:MathController.php

use Illuminate\Support\Facades\View;

class MathController extends Controller
{
    public function multiply($x, $y) {
        $result = $x * $y;
        return View::make('output', ['x'=>$x, 'y'=>$y, 'result'=>$result]);
    }
}     

web.php

Laravel 8.x以上の場合

use App\Http\Controllers\MathController;

Route::get('/multiplication/{x}/{y}/', [MathController::class, 'multiply']);

または

Route::get('/multiplication/{x}/{y}/', 'App\Http\Controllers\MathController@multiply');

Laravel 7.x以下の場合

Route::get('/multiplication/{x}/{y}/', 'MathController@multiply');

例:output.blade.php

<p>{{ $x }} * {{ $y }} = {{ $result }}</p>