从Laravel控制器向Routes发送数据;视图


Sending data from Laravel Controller to Routes & View

我已经使用Auth::login($user)发送了一个变量,并在我的路由中设置了一个数组。想要发送一个额外的数组,我尝试的一切都失败了。

代码

控制器

public function callback(){
        if( !$this->fb->generateSessionFromRedirect() ){
            return Redirect::to('/')->with('message', "Error logging into facebook");
        }
        $user_fb = $this->fb->getGraph();
        if(empty($user_fb)) {
            return Redirect::to('/')->with('message', "User Not Found");
        }
        $user = User::whereUidFb($user_fb->getProperty('id'))->first();
        if(empty($user)){
            $user = new User;
            $user->name = $user_fb->getProperty('name');
            $user->uid_fb = $user_fb->getProperty('id');
            $user->save();
        }
        $user->access_token_fb = $this->fb->getToken();
        $user->save();
        $user_pages = $this->fb->getPages();
        // var_dump($user_pages);
        Auth::login($user);
        return Redirect::to('/')->with(array('pages' => $user_pages));
    }

Route::get('/', function()
{
    $user = array();
    if(Auth::check()) {
        $user = Auth::user();
    }
    return View::make('hello', array('user' => $user));
});

所以我想发送$user_pages,现在我只能访问$user。尝试在我的视图中运行$pages的foreach循环,但没有识别变量。所以我猜我必须在路由中做一些事情,并以发送$data的方式发送它。

帮忙吗?

with方法将数据保存到会话中,因此需要使用session('key');

控制器:

public function callback(){
    //.......
    return Redirect::to('/')->with('pages', $user_pages);
    //.......
}

:

Route::get('/', function() {
    //From session
    $user_pages = Session::get('pages'); //session('pages'); for laravel >= 5.0
    $data = array();
    if(Auth::check()) {
        $data = Auth::user();
    }
    return View::make('hello', array('data' => $data));
});