Artisan command dùng model instance trong controller actions Laravel Chuyên mục PHP và Laravel 2023-09-09 753 Lượt xem 5 Lượt thích 0 Bình luận

Đây là một mẹo nhỏ về artisan command để tạo controller. Vì vậy, nếu bạn đã sử dụng lệnh make:controller với tùy chọn --resource, nó sẽ tạo ra các controller có các create, read, update, and delete (“CRUD”) actions trong đó.
Nhưng đây là một điều. Khi bạn controller bằng lệnh này, các hành động như hiển thị, chỉnh sửa, cập nhật và hủy sẽ sử dụng id của tài nguyên cho mục đích cập nhật.
Ví dụ: nếu bạn tạo UserController bằng lệnh này, nó sẽ tạo controller với các action tương tự như sau.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
//
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
Như bạn có thể thấy, một số phương phức ở đây đang sử dụng $id để xác định tài nguyên.
Nhưng bạn có thể muốn sử dụng một model instance instead thay vì id khi sử dụng route model binding. Bạn sẽ làm gì trong trường hợp đó?
Using model instance in make:controller
Nếu bạn muốn sử dụng model instance thay vì id khi tạo controller, bạn có thể sử dụng tùy chọn --model với make:controller bằng cách chuyển vào model name.
Vì vậy, ví dụ: nếu chúng ta sử dụng instance của model Người dùng trong ví dụ trước, chúng ta có thể sử dụng lệnh sau như sau.
php artisan make:controller UserController --resource --model User
Điều này sẽ tạo ra UserController với nội dung như sau.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
//
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show(User $user)
{
//
}
public function edit(User $user)
{
//
}
public function update(Request $request, User $user)
{
//
}
public function destroy(User $user)
{
//
}
}
Như bạn có thể biết, các phương thức show, edit, update, và destroy hiện đang được đưa vào model’s instance App\Models\User thay vì id.

Bình luận (0)