この記事では、LaravelでHello World!を出力する方法について書いていきます。
方法
方法については3パターンあります。
- 表示ファイルに直接書く
- bladeファイルを使う
- コントローラーを使う
する方法です。
方法①表示ファイルに直接書く
直接書いた場合は簡単です。
http://localhost/プロジェクト名/public
にアクセスしてください。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>方法②bladeファイルを使う
まず、hello.blade.phpを作成します。階層は、resources/views ディレクトリ内です。
そして以下のように記述します。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>{{ $message }}</h1>
</body>
</html>
そして、routes/web.phpを開き以下のように記述します。
<?php
use Illuminate\Support\Facades\Route;
Route::get('/hello', function () {
return view('hello', ['message' => 'Hello World!']);
});
コードの解説
http://localhost/プロジェクト名/public/hello
のurlにアクセスしたら、変数messaseにHello world!を渡す。という流れになっています。
Route::get('/hello', function () {
return view('hello', ['message' => 'Hello World!']);
});
方法③コントローラーを使う
ターミナルで以下のコマンドを実行し、HelloControllerという名前のコントローラーを作ります。
php artisan make:controller HelloController
app/Http/Controllers/HelloController.phpを開き、indexメソッドを追加して「Hello World」を返すように書きます。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HelloController extends Controller
{
public function index()
{
return 'Hello World';
}
}
そして、routes/web.phpを開き以下のように記述します。
<?php
use App\Http\Controllers\HelloController;
Route::get('/hello', [HelloController::class, 'index']);
http://localhost/プロジェクト名/public/hello
にアクセスしたら表示することができます。

