passing data to a view laravel

我怕爱的太早我们不能终老 提交于 2019-12-02 19:59:10

问题


Just getting to mvc frameworks and im trying to pass data to my view using blade template engine.

here's my routes file

Route::get('/', 'PagesController@index');

my PagesController

<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class PagesController extends Controller {

    public function index() {

        return view('index');

        $url = 'example.com';
    }

    public function about() {


        return 'hello';


    }

}

my index.blade.php file

<h1>{{ $url }}</h1>

I get the Undefined variable: url error message. What am i doing wrong?


回答1:


Try this

public function index() {
   $url = 'example.com';
   return view('index', ['url' => $url]); 
}

Initialize the variable and send it as a parameter to the view.




回答2:


you can also pass data to view by using multiple with.

return View::make('blog')->with('posts', $posts)->with('anotherPost',$anotherPost);


you can always make multiple with or can pass values via array. whatever you think is best.



来源:https://stackoverflow.com/questions/34701429/passing-data-to-a-view-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!