Most times the operations we carry out on a model in our application are create
, read
, update
, and delete
, as far as interacting with the database is concerned.
The simplest way to execute such an operation is by creating a resource controller, which appropriately routes all HTTP requests for CRUD operations to the controller.
To create a post resource controller, paste the code below in your route:
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
Then, run
php artisan make:controller PostController --resource
, which will create a resource, PostController
.
Resource controllers provide a simple way to handle CRUD operations with less hassle.
For example, say you want to create a post with a resource controller. You first display the form before storing it. In the create
method in the controller, you return the view, and your URI
should be /create
. Then, while trying to store the values of your form, you should send a POST
request to /store
.