passing data to a view laravel

2020-05-07 06:19发布

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?

2条回答
Evening l夕情丶
2楼-- · 2020-05-07 06:32

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.

查看更多
我只想做你的唯一
3楼-- · 2020-05-07 06:48

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.

查看更多
登录 后发表回答