目次

21 Laravel Controller作成からViewまで

Controller作成

$ php artisan make:controller HelloWorld

$ ll app/Http/Controllers/HelloWorld.php 
-rw-r--r-- 1 matsui users 117 Mar 19 16:36 app/Http/Controllers/HelloWorld.php

app/Http/Controllers/HelloWorld.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HelloWorld extends Controller
{
    public function hello()
    {   
        $hello = 'Hello World.';
        $hello_array = ['aaa','bbb','ccc'];

        return view('hello', compact('hello', 'hello_array'));
    }   
}

Route追加

routes/web.php

Route::get('/hello','HelloWorld@hello');

View追加

resources/views/hello.blade.php

<!-- resources/view/contact.blade.php -->
 
<!DOCTYPE HTML>
<html>
<head>
    <title>contact</title>
</head>
<body>
    <h1>{{$hello}}</h1>
    @foreach ($hello_array as $h) 
    {{$h}}
    @endforeach
</body>
</html>

Webからアクセス

http://example.com/hello