MasterPHP.in
Try Compiler →
Laravel Tutorial

Laravel Resource Controllers: Full CRUD Structure


Your invoicing app needs to list invoices, show one invoice, create a new one, edit it and delete it. Then the same set of actions is needed for clients, and then for payments. If every developer on the team invents their own method names, you end up with addInvoice, new_client, removePayment and delete in different controllers. Nobody can guess where anything lives.

Laravel solves this with a standard. Almost every data-driven page you will ever build falls into the same seven actions, and Laravel gives each action a fixed method name and a fixed URL pattern. A controller built on this standard is called a resource controller.

In this lesson you will learn what the seven methods do, how to generate them with one Artisan command and how to write each of them in your invoice controller.

 

The Seven Standard Actions

CRUD stands for Create, Read, Update and Delete, the four things you do with data. Laravel splits these four jobs into seven controller methods, because creating and editing each need two steps: one to show a form and one to save it.

Here are the seven actions for an invoices resource:

GET        /invoices                  invoices.index     index()
GET        /invoices/create           invoices.create    create()
POST       /invoices                  invoices.store     store()
GET        /invoices/{invoice}        invoices.show      show()
GET        /invoices/{invoice}/edit   invoices.edit      edit()
PUT/PATCH  /invoices/{invoice}        invoices.update    update()
DELETE     /invoices/{invoice}        invoices.destroy   destroy()

You met these routes and their names in the Resource Routes & route:list lesson. This lesson looks at the other side: the controller that sits behind them. Learn this list well, because every resource in the rest of the course follows it.

 

Methods That Show Data

  • index() shows the list of all invoices
  • show() shows one invoice, chosen by the {invoice} value in the URL

Both use the GET verb because they only read data and never change it.

 

Methods That Show Forms

  • create() shows an empty form for a new invoice
  • edit() shows a form filled with the current values of one invoice

These also use GET. They only display a page. Later, in the Blade Templating chapter, these methods will return real views with HTML forms.

 

Methods That Change Data

  • store() receives the submitted create form and saves a new invoice
  • update() receives the submitted edit form and saves the changes
  • destroy() deletes the invoice

These three never show a page of their own. They do the work and then send the visitor somewhere else, usually back to the list. Redirects are covered in the Redirects & Flash Session Data lesson.

The create and edit flows always work in pairs:

Create:   GET /invoices/create   -->  create()  shows the form
          POST /invoices         -->  store()   saves the data

Edit:     GET /invoices/5/edit   -->  edit()    shows the filled form
          PUT /invoices/5        -->  update()  saves the changes

Notice that the URL for create() and store() is almost the same. The difference is the HTTP verb: GET shows, POST saves. This is why the same address can do two different jobs.

 

Generating a Resource Controller

Add the --resource option to the command you used in the last lesson:

php artisan make:controller InvoiceController --resource

You already created InvoiceController last time, so Artisan will refuse with this message:

ERROR  Controller already exists.

For this lesson, add --force to replace the old file. This deletes whatever was in it, which is fine here because we will write the full controller again below:

php artisan make:controller InvoiceController --resource --force

Open the new file. Laravel has generated all seven methods with empty bodies:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index()
    {
        //
    }

    public function create()
    {
        //
    }

    public function store(Request $request)
    {
        //
    }

    public function show(string $id)
    {
        //
    }

    public function edit(string $id)
    {
        //
    }

    public function update(Request $request, string $id)
    {
        //
    }

    public function destroy(string $id)
    {
        //
    }
}

Laravel also adds a short comment above each method, which is removed here to save space.

Two details are worth noticing. First, store() and update() receive a Request $request argument. This object holds the data sent from a form, and you will learn how to use it in the Request Object lesson in the next chapter. Second, the generated methods call the route value $id. It is better to rename it to $invoice, so the argument matches the {invoice} placeholder in the URL.

 

Filling in the Methods

You do not have a database yet, so saving and deleting cannot really happen. For now each method will return a short message, and index() and show() will keep using the sample data from the last lesson. This lets you see the structure clearly. The real saving will arrive in the Database and Eloquent chapters.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index()
    {
        return $this->invoices();
    }

    public function create()
    {
        return 'Show the form to create a new invoice';
    }

    public function store(Request $request)
    {
        return 'Save the new invoice';
    }

    public function show(int $invoice)
    {
        $data = $this->invoices()[$invoice] ?? abort(404);
        $gst = $data['amount'] * 0.18;

        return [
            'invoice' => $invoice,
            'client'  => $data['client'],
            'amount'  => $data['amount'],
            'gst'     => $gst,
            'total'   => $data['amount'] + $gst,
        ];
    }

    public function edit(int $invoice)
    {
        return "Show the form to edit invoice {$invoice}";
    }

    public function update(Request $request, int $invoice)
    {
        return "Update invoice {$invoice}";
    }

    public function destroy(int $invoice)
    {
        return "Delete invoice {$invoice}";
    }

    private function invoices(): array
    {
        return [
            1001 => ['client' => 'Sharma Traders', 'amount' => 12500],
            1002 => ['client' => 'Patel Stationers', 'amount' => 8400],
            1003 => ['client' => 'Iyer Electricals', 'amount' => 21000],
        ];
    }
}

When a method needs both the request and a route value, as update() does, Laravel handles both for you. The Request object is given to you automatically, and the route value comes from the URL. The order of the two arguments in your own methods is not important, but keeping $request first is the common habit.

Later, create() and edit() will return Blade views, and store(), update() and destroy() will end with a redirect. The shape of the controller will not change.

 

Registering the Routes

Now remove the two separate invoice routes you wrote in the last lesson from routes/web.php, and replace them with a single line:

use App\Http\Controllers\InvoiceController;

Route::resource('invoices', InvoiceController::class);

This one line registers all seven routes from the list above, with the names invoices.index, invoices.show and so on. Because the resource is called invoices, Laravel names the route value {invoice}, which is why we renamed the method arguments to match.

If you do not need all seven actions, you can limit them with only() or except(). These options, along with custom names, were covered in the Resource Routes lesson, so we will not repeat them here.

 

Testing What You Built

Run php artisan route:list to confirm that the seven routes point to InvoiceController. Then start the server with php artisan serve and open these addresses:

http://localhost:8000/invoices
http://localhost:8000/invoices/1001
http://localhost:8000/invoices/create
http://localhost:8000/invoices/1001/edit

All four use GET, so the browser address bar can reach them. The other three actions, store, update and destroy, need POST, PUT and DELETE, and a browser cannot send those just by typing a URL. They also need a CSRF token, which protects your forms from forged requests. You will build real forms for them in the Forms & Validation chapter, so for now it is enough to see them in route:list.

 

Resource Controllers and API Controllers

When you build a JSON API, there are no HTML forms, so create() and edit() are not needed. Laravel has a shorter version for that:

php artisan make:controller Api/InvoiceController --api

This generates only five methods: index, store, show, update and destroy. The matching route helper is Route::apiResource(). You will use both in the Building REST APIs chapter.

 

Adding Your Own Methods

A resource controller is not limited to seven methods. If you need an extra action, for example exporting invoices to PDF, you can add a new method to the same controller. The route for it must be defined before Route::resource():

Route::get('/invoices/export', [InvoiceController::class, 'export'])
    ->name('invoices.export');

Route::resource('invoices', InvoiceController::class);

The order matters because of the GET /invoices/{invoice} route. If it is registered first, it will treat the word export as an invoice number. Putting your specific route first lets it match before the general one.

If you find yourself adding many extra methods, that is a sign that the controller may be doing too many jobs. You will see how to deal with that in the lesson on keeping controllers thin.

 

Common Mistakes

Mistake 1: Defining a Custom Route After the Resource

Route::resource('invoices', InvoiceController::class);
Route::get('/invoices/export', [InvoiceController::class, 'export']);

Visiting /invoices/export runs show() with the text export as the invoice value, and because show() expects an integer, you see:

TypeError: App\Http\Controllers\InvoiceController::show(): Argument #1 ($invoice) must be of type int, string given

Move your custom route above Route::resource().

 

Mistake 2: Deleting a Method the Route Still Uses

You decide you do not need create() and remove the method, but Route::resource() still registers its route. Visiting /invoices/create gives:

BadMethodCallException: Method App\Http\Controllers\InvoiceController::create does not exist.

Either put the method back, or tell the route not to register it with ->except(['create']).

 

Mistake 3: Submitting an Edit Form with POST

Browsers can only send GET and POST from an HTML form. If your edit form posts to /invoices/1001 without telling Laravel that it means PUT, you get:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The POST method is not supported for route invoices/1001. Supported methods: GET, HEAD, PUT, PATCH, DELETE.

Laravel solves this with method spoofing, a hidden field inside the form. You will learn it in the HTML Forms, CSRF & Method Spoofing lesson.

 

Mistake 4: 419 Page Expired

When a form posts to a web route without a CSRF token, Laravel rejects the request and shows a page that says 419 | Page Expired. This protection is intentional. The fix is to include the CSRF token inside every form, which is also part of the forms lesson.

 

Mistake 5: Running make:controller on an Existing File

ERROR  Controller already exists.

Artisan will not overwrite your work by accident. Use --force only when you are sure you want to replace the file, because everything you wrote in it will be lost.

 

Mistake 6: Putting All the Logic in store() and update()

It is easy to write validation, saving, emailing and PDF creation inside store() because it is the place where “everything happens”. The method becomes 80 lines long and nobody wants to touch it. Keep the controller methods short, and move real work into other classes as you learn them in later chapters.

 

Quick Summary

  • A resource controller has seven standard methods: index, create, store, show, edit, update and destroy.
  • index and show display data, create and edit display forms, and store, update and destroy change data.
  • Creating and editing are always two steps: GET shows the form, then POST or PUT saves it.
  • Generate a resource controller with php artisan make:controller InvoiceController --resource.
  • Register all seven routes with Route::resource('invoices', InvoiceController::class).
  • Rename the generated $id arguments to match the route placeholder, like $invoice.
  • Use --api and Route::apiResource() for APIs, which skip create and edit.
  • Define custom routes before Route::resource(), or the {invoice} route will catch them first.
  • Browsers can only send GET and POST, so forms need method spoofing and a CSRF token. You will learn both later.

 

What’s Next

A resource controller is ideal when one controller manages a full set of actions. But sometimes a controller needs to do only one thing, such as downloading an invoice PDF or handling a Razorpay webhook. Creating seven methods for that would be wasteful. In the next lesson, Single Action (Invokable) Controllers, you will learn how to build a controller with just one method.

Frequently Asked Questions

They do two different jobs that work together. The Artisan command creates the controller file with the seven empty methods, and Route::resource registers the seven routes that point to those methods. You normally use both for the same resource.
Creating needs two separate steps. The first shows an empty form to the user, which is a GET request, and the second receives the submitted data and saves it, which is a POST request. Keeping them in separate methods keeps each method short and easy to understand. The same idea applies to edit and update.
No. If a resource does not need a particular action, you can leave it out of the routes with only or except. For example, a payment history page may only need index and show, since payments are never edited by hand. You can also delete the unused methods from the controller.
In theory, PUT replaces the whole record and PATCH changes only some of its fields. Laravel sends both to the same update method, so you do not have to choose in your controller. Most Laravel forms send PUT, and APIs sometimes use PATCH for partial changes.
Yes, a controller can have as many methods as you like. Just register the route for your extra method before the Route::resource line so it is not caught by the show route. If you add too many extra methods, consider moving them into a separate controller.

Share this tutorial