如何在LARAVEL中使用PHP的“紧凑”功能来使用视图

时间:2017-03-18 11:25:43

标签: php laravel function laravel-5

我正在使用laravel从数据库中获取数据并将数据或数据数组存储到变量中,例如$ tasks存储数据库中任务表的数据,直到一切正常,但在处理$ task变量时,这是必要的使用“紧凑”功能?

任何人都可以解释这个

Route::get('/test', function () {

$data   =   [
                'name'  =>  'Vrushal',
                'last'  =>  'Raut',
                'tasks' =>  [
                                'Programming',
                                'UI/UX Developement',
                                'Cloud Expert'
                            ]
            ];
            //return view('templates/test', compact($data)); //NOT WORKING
            //return view('templates/test', $data); // ITS WORKING
            return View::make('templates/test',$data); // ITS WORKING
}); 

与数据库plz一起解释这个

Route::get('/tasks', function(){

$tasks  =   DB::table('tasks')->get();

return view('templates/tasks', compact('tasks')); // ITS WORKING
//return View::make('templates/test',$tasks); // NOT WORKING
});

提前致谢!

3 个答案:

答案 0 :(得分:2)

compact('data')['data' => $data]相同,因此为了能够访问Vrushal值,您需要在视图中执行此操作:

{{ $data['name'] }}

执行此操作时:

 View::make('templates/test', $data);

您可以通过以下方式获取Vrushal值:

{{ $name }}

答案 1 :(得分:2)

compact - 创建包含变量及其值的数组 手动http://php.net/manual/en/function.compact.php

<?php

$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$result = compact("event", "city", "state");
print_r($result);
//return view('templates/test', compact("event", "city", "state")); // ITS WORKING

结果

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)
$arr = array(
    "city"  => "San Francisco",
    "state" => "CA",
    "event" => "SIGGRAPH"
);

extract($arr);    
$result = compact(array_keys($arr));
print_r($result);
//return view('templates/test', compact(array_keys($arr)); // ITS WORKING

结果

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)
$arr = array(
     "city"  => "San Francisco",
     "state" => "CA",
     "event" => "SIGGRAPH"
);
print_r($arr);
//return view('templates/test', $data); // ITS WORKING

结果

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)
$arr = array(
     "city"  => "San Francisco",
     "state" => "CA",
     "event" => "SIGGRAPH"
);
$result = compact($arr);
print_r($result);
//return view('templates/test', compact($arr)); //NOT WORKING

结果

Array
(

)

答案 2 :(得分:1)

//return view('templates/test', compact($data)); //NOT WORKING它无效,因为您不需要美元符号来表示紧凑元素。它应该是这样的:

return view('templates.test', compact('data'));然后您可以通过视图中的$ data []变量访问它。

其他方式:

return view('templates.test')->with('variable', $data);并使用$variable[]

访问此视图