Bài 12: Truyền tham số từ Controller sang View - Học lập trình Laravel

Đăng bởi: Admin | Lượt xem: 13072 | Chuyên mục: Laravel


Để truyền dữ liệu ra View (Passing Data to Views) chúng ta có các cách như sau:

1. Dùng compact()

Cú pháp:
compact('tencuabientruyenvao')
Ví dụ:
Route::get('chao/{user}', function ($user) {
    return view('hello-user', compact('user'));
});
// view muon hien thi thi goi bien $user

2. Dùng with()

Cú pháp:
view('tenview')->with('key', 'value');
Ví dụ:
Route::get('chao/{user}', function ($user) {
    return view('hello-user')->with('user', $user);
});

//de hien thi trong view goi bien $user

3. Dùng mảng

Cú pháp:
view('tenview', ['key' => 'value']);
Ví dụ:
Route::get('chao/{user}', function ($user) {
    return view('hello-user', ['user' => $user]);
});
Bài tiếp theo: Form Request trong Laravel >>
vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!