2015-05-13 18 views
10

Chào các bạn Tôi mới dùng Laravel và tôi đã cố gắng lưu trữ tất cả các bản ghi của bảng 'sinh viên' thành một biến và sau đó chuyển biến đó sang một khung nhìn để tôi có thể hiển thị chúng.Truyền dữ liệu từ bộ điều khiển để xem trong Laravel

Tôi có một bộ điều khiển - ProfileController và bên trong một hàm:

public function showstudents() 
    { 
    $students = DB::table('student')->get(); 
    return View::make("user/regprofile")->with('students',$students); 
    } 

Theo quan điểm của tôi, tôi có mã này

<html> 
    <head></head> 
    <body> Hi {{Auth::user()->fullname}} 
    @foreach ($students as $student) 
    {{$student->name}} 

    @endforeach 


    @stop 

    </body> 
    </html> 

Tôi nhận được lỗi này: biến Không xác định: học sinh (Xem: regprofile.blade.php)

Trả lời

11

Bạn có thể thử điều này không,

return View::make("user/regprofile", compact('students')); OR 
return View::make("user/regprofile")->with(array('students'=>$students)); 

Trong khi, bạn có thể thiết lập nhiều biến một cái gì đó như thế này,

$instructors=""; 
$instituitions=""; 

$compactData=array('students', 'instructors', 'instituitions'); 
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions); 

return View::make("user/regprofile", compact($compactData)); 
return View::make("user/regprofile")->with($data); 
+0

không, không hoạt động: ( – VP1234

+0

bạn có gặp lỗi tương tự không? –

+0

có, sinh viên biến không xác định – VP1234

0

Hãy thử với mã này:

return View::make('user/regprofile', array 
    (
     'students' => $students 
    ) 
); 

Hoặc nếu bạn muốn vượt qua các biến hơn vào xem:

return View::make('user/regprofile', array 
    (
     'students' => $students, 
     'variable_1' => $variable_1, 
     'variable_2' => $variable_2 
    ) 
); 
6

Để truyền một biến duy nhất để xem.

Bên trong bộ điều khiển của bạn tạo ra một phương pháp như:

function sleep() 
{ 
     return view('welcome')->with('title','My App'); 
} 

Trong Tuyến đường của bạn

Route::get('/sleep', '[email protected]'); 

Trong Xem bạn Welcome.blade.php. Bạn có thể echo biến của bạn như {{ $title }}

Đối với An Array (nhiều giá trị) thay đổi, phương pháp ngủ để:

function sleep() 
{ 
     $data = array(
      'title'=>'My App', 
      'Description'=>'This is New Application', 
      'author'=>'foo' 
      ); 
     return view('welcome')->with($data); 
} 

Bạn có thể truy cập vào bạn biến như {{ $author }}.

-1

Tôi cho rằng việc truyền dữ liệu từ bộ điều khiển sang chế độ xem là xấu. Bởi vì nó không thể tái sử dụng và làm cho điều khiển béo hơn. Chế độ xem nên được chia thành 2 phần: mẫu và trình trợ giúp (có thể lấy dữ liệu từ bất kỳ đâu). Bạn có thể tìm kiếm nhà soạn nhạc xem trong laravel để biết thêm thông tin.

Các vấn đề liên quan