Laravel — P58: Resource Controllers

Simplify CRUD with resource controllers

There are a set of repetitive tasks that occur on most resources. If you wanted to display cameras on your web-application, you would most likely want to:

  • View all Camera
  • See a form to insert a new camera
  • Process the camera insertion
  • Retrieve a particular camera
  • See a form to update a camera (with fields already pre-populated)
  • Process the update
  • Delete a camera

https://www.dinocajic.com/laravel-p57-controller-middleware/

What if we stepped and looked at the characteristics of a camera, like the camera’s brand and model. We could have a resource controller for each of those as well where we manage the brands and the models. We could even pick a different object, like a computer, and do the same stuff.

Resource controllers are standardized this way for a reason: because they just work for most scenarios.

In fact, it’s so standardized in Laravel, that Laravel has a built in artisan command to create resource controllers.

# php artisan make:controller CameraController --resource

   INFO  Controller [app/Http/Controllers/CameraController.php] created successfully.  

#

Open up your newly created CameraController to see all of the methods that Laravel has created for you.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CameraController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

How nice is that? It even knows which arguments each method needs and takes care of type-hinting dependencies for you.

The resource controller gets special method names for each action. We’ve already looked at these before.

Verb      URI                  Action  Route Name
GET       /cameras              index   cameras.index
GET       /cameras/create       create  cameras.create
POST      /cameras              store   cameras.store
GET       /cameras/{photo}      show    cameras.show
GET       /cameras/{photo}/edit edit    cameras.edit
PUT/PATCH /cameras/{photo}      update  cameras.update
DELETE    /cameras/{photo}      destroy cameras.destroy

Without going too far into it, we’ve created routes for this before during the PersonalCarController section.

Route::prefix('/personalcars')->group(function() {
    Route::get('/',          [PersonalCarController::class, 'index']);
    Route::get('/create',    [PersonalCarController::class, 'create']);
    Route::post('/',         [PersonalCarController::class, 'store']);
    Route::get('/{id}',      [PersonalCarController::class, 'show']);
    Route::get('/{id}/edit', [PersonalCarController::class, 'edit']);
    Route::put('/{id}',      [PersonalCarController::class, 'update']);
    Route::delete('/{id}',   [PersonalCarController::class, 'destroy']);
});

https://medium.com/geekculture/laravel-p41-controller-show-method-cmp-d503973018e7

However, since it is such a common topic, we don’t have to create our own routes…we can let Laravel handle that for us.

use App\Http\Controllers\CameraController;

Route::resource('cameras', CameraController::class);

Creating the views. You will need to have the following blade files created:

  • index.blade.php
  • create.blade.php
  • show.blade.php
  • edit.blade.php

We can then return those through our resource controller. I’ll create the index.blade.php file for demonstration purposes. It will just accept an an argument, the make of the camera, and display it. The index.blade.php file will live under the resources/views/cameras/ directory.

Camera: {{ $make }}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CameraController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response()->view('cameras.index', [
            'make' => 'Canon',
        ]);
    }

    // ...
}

 

I’ll return the view from our index method and we should see Camera: Canon.

If you ever forget which routes you have, you can use the php artisan route:list command to see all of your routes.

https://github.com/dinocajic/youtube-laravel

 

Laravel Series

Continue your Laravel Learning.

Laravel — P57: Controller Middleware

Secure actions with controller-level middleware

Laravel – P57: Middleware In Controllers

In part 57 of our Laravel series, discover how to register and apply middleware directly within controllers. Learn to secure sensitive actions, share common logic, and override route defaults for concise, maintainable code.

Laravel — P58: Resource Controllers

Simplify CRUD with resource controllers

Laravel – P58: Resource Controllers

In part 58 of our Laravel fundamentals series, learn how resource controllers streamline CRUD operations. Explore generator commands, automatic RESTful routes, customizing actions, and keeping your controllers clean and maintainable. (233 characters)

 

Laravel — P59: Partial Resource Routes

Register only what you need with partial resource routes

Laravel – P59: Partial Resource Routes

In part 59 of our Laravel fundamentals series, discover how partial resource routes let you register only the endpoints you need. Learn the only and except options, group route patterns, and keep your routing file lean and secure.

Leave a Reply