#Note: Laravel best practices

- Controller, Model
Nên đẩy phần logic của ứng dụng vào trong Repository cho Model và Service cho Controller, việc của Controller chỉ là điều hướng cho ứng dụng.
Ví dụ:
Không nên:
public function index()
{
$clients = Client::verified()
->with(['orders' => function ($q) {
$q->where('created_at', '>', Carbon::today()->subWeek());
}])
->get();
return view('index', ['clients' => $clients]);
}
—
public function store(Request $request)
{
if ($request->hasFile('image')) {
$request->file('image')->move(public_path('images') . 'temp');
}
....
}
Nên:
public function index()
{
return view('index', ['clients' => $this->client->getWithNewOrders()]);
}
class Client extends Model
{
public function getWithNewOrders()
{
return $this->verified()
->with(['orders' => function ($q) {
$q->where('created_at', '>', Carbon::today()->subWeek());
}])
->get();
}
}
—
public function store(Request $request)
{
$this->articleService->handleUploadedImage($request->file('image'));
....
}
class ArticleService
{
public function handleUploadedImage($image)
{
if (!is_null($image)) {
$image->move(public_path('images') . 'temp');
}
}
}
2. Validation
Tùy trong các tình huống khác nhau, chúng ta nên đẩy phần validate các request vào trong 1 class khác để xử lý, thay vì xử lý nó trong Controller (Nếu khi viết API có thể không nhất thiết tách, ta có thể viết thành 1 RULE chung thay vì tách ra).
Ví dụ:
Không nên:
public function store(Request $request)
{ $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
]); // say something ...
}
Nên:
public function store(PostRequest $request)
{
// say something ...
}
class PostRequest extends Request
{
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
];
}
}
Xem thêm: