Home > front end >  Generic Model Based CRUD API Laravel
Generic Model Based CRUD API Laravel

Time:09-18

Is there a built in or library based way to implement generic Eloquent/Model based views in Laravel for simple CRUD endpoints?

At the moment I am writing the logic for index, store, destroy, update manually, but all the code is essentially the same.

e.g.

public function destroy($id)
{
  $customer= CustomerInfo::find($id);
  $customer->delete();
}  

I'm more used to Django and the DRF which implements a ModelViewSet class which handles all (most) of the logic for simple CRUD applications.

CodePudding user response:

Implement generic Eloquent/Model based views in Laravel for simple CRUD endpoints

I'm not sure about that but Laravel provides route to model binding, which shortens your code. There's also resource controller which is already pretty much declare all needed methods for you. What's left is quite minimal. So after using model binding and resource controller, your destroy() method may look like:

public function destroy(CustomerInfo $customerInfo)
{
  $customerInfo->delete();
} 

But the method name and its agrument is already declared like a placeholder, you just write delete() line. More about model binding and resource controller

CodePudding user response:

Use single artisan command to have CRUD endpoints all in one.

php artisan make:controller PhotoController --resource

Because of this common use case, Laravel resource routing assigns the typical create, read, update, and delete ("CRUD") routes to a controller with a single line of code. To get started, we can use the make:controller Artisan command's --resource option to quickly create a controller to handle these actions:

  • Related