0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel8 コントローラの使い方

Last updated at Posted at 2021-10-07

Laravelにおけるコントローラクラスを理解しよう
人気のPHPフレームワークLaravelを習得しよう 第4回
https://codezine.jp/article/detail/11524

こちらで勉強しててLaravel8ではハマったのでメモします。
おそらく記事はver8以前の記述ではないかと思います。

#1.実装内容(エラー版)
ページに記載通りに
①Control Class

\app\Http\Controllers\HelloBladeWithDataController.php
<?php
namespace App\Http\Controllers;  // (1)

use App\Http\Controllers\Controller;  // (2)

class HelloBladeWithDataController extends Controller  // (3)
{
	public function __invoke()  // (4)
	{
		$data["name"] = "武者小路";  // (5)
		return view("helloWithData", $data);  // (5)
	}
}

②web.php

web.php
Route::get("/chap4/helloBladeWithData", "HelloBladeWithDataController");

③View Class

\resources\views\helloWithData.blade.php
<?php
namespace App\Http\Controllers;  // (1)

use App\Http\Controllers\Controller;  // (2)

class HelloBladeWithDataController extends Controller  // (3)
{
	public function __invoke()  // (4)
	{
		$data["name"] = "武者小路";  // (5)
		return view("helloWithData", $data);  // (5)
	}
}

#2.エラー内容
◆メッセージ
UnexpectedValueException
Invalid route action: [HelloBladeWithDataController].

◆イメージ
image.png

#3.原因
Larave8でWeb.phpの記載ルールが変わった模様。。

#4.対処法

web.php
// エラー例
//Route::get("/chap4/helloBladeWithData", "HelloBladeWithDataController");
// 正解
Route::get("/chap4/helloBladeWithData", \App\Http\Controllers\HelloBladeWithDataController::class);

#5.おまけ invoke使わない例

url control class control method
/chap4/helloMusha \App\Http\Controllers\Chap4Controller helloMusha
/chap4/helloNakano 同上 helloNakano
\app\Http\Controllers\Chap4Controller.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class Chap4Controller extends Controller
{
	public function helloMusha()  // (1)
	{
		$data["name"] = "武者小路";  // (2)
		return view("helloWithData", $data);  // (2)
	}
	public function helloNakano()  // (3)
	{
		$data["name"] = "中野";  // (4)
		return view("chap3.hello", $data);  // (4)
	}
}
web.php
Route::get("/chap4/helloMusha", [\App\Http\Controllers\Chap4Controller::class,'helloMusha']);
Route::get("/chap4/helloNakano", [\App\Http\Controllers\Chap4Controller::class,'helloNakano']);

#参考元

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?