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.

【Laravel】コントローラから、テンプレートへの値の受け渡しメモ

Last updated at Posted at 2020-08-07

コントローラから、viewテンプレートへ値を受け渡したいときは、複数の方法で記述できます。

基本的には、コントローラのメソッドで

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SampleController extends Controller
{
    public function index()
    {
        // 
        return view('テンプレート情報', 配列);
    }
}

indexメソッドのreturn以下のように、view関数の第1引数にテンプレート情報、第2引数にテンプレート側に送る配列を用意します。

例えば、

class SampleController extends Controller
{
    public function index()
    {
        // 
        return view('index', ['message' => 'メッセージです。']);
    }
}

こんな感じで記述すると、第2引数のキーであるmessageがviewテンプレート側で変数名として使用され、その変数にメッセージです。の値が用意される、という感じになります。

また、このreturn view()をスッキリしたコードにするためにcompact関数を使用することもお勧めです。

class SampleController extends Controller
{
    public function index()
    {
        $message = [
             'message' => 'メッセージです。'
        ];

        return view('index', compact('message') );
    }
}

view関数内に連想配列を書く必要がないので、見やすくなると思います。

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?