How to Create a CRUD REST API in Laravel 8 with Sanctum

How to Create a CRUD REST API in Laravel 8 with Sanctum

Admin
Admin・ 23 September 2021
11 min read ・ 30878 views
Series: Laravel Sanctum

REST API CRUD Laravel 8 Sanctum - Continuing the previous tutorial article, namely creating REST API authentication in laravel 8 with sanctum, in this article I will share a tutorial on how to create a CRUD REST API using sanctum.

Read: Laravel 8: REST API Authentication with Sanctum

In this tutorial, we simulate to create a REST API CRUD Data Program. Just imagine that we have a Learning Management System or LMS, and we want to manage program data in that LMS using a REST API created using the Sanctum package in Laravel 8.

Okay, let's get straight to coding.👇 👨‍💻

Step 1: Add Sanctum Middleware

 \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

We have to add sanctum middleware to api middleware group inside app/Http/Kernel.php file. This middleware is responsible for ensuring that every incoming request can be authenticated using a laravel session cookie, while still allowing requests from third parties to be authenticated using an API token.

Step 2: Create Model & Migration

php artisan make:model Program -m

In this second step we need to create model and migration files for the Program. Run the artisan command as above to generate two Program files model and migration.

protected $guarded = [];

After successfully generating the model program file, now open the file and add the code above.

 public function up()
    {
        Schema::create('programs', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('desc');
            $table->timestamps();
        });
    }

Next we need to setup the program migration file that was generated earlier. Open the file in the database/migrations/xxxx_xx_xx_xxxxxx_create_programs_table.php directory. Then in the up method, change the code to be like the example above. In this migrations program file, we only add two fields, namely name and desc.

php artisan migrate

If you have finished the migration file setup, now run the php artisan migrate command to migrate all migration files to the database.

Step 3: Create API Resource

php artisan make:resource ProgramResource

To create or generate a resource class, we can use the artisan make:resource command as above. By default, the resource will be placed in the app/Http/Resources directory of our application or laravel project. The resource API will extend the Illuminate\Http\Resources\Json\JsonResource class.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProgramResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'desc' => $this->desc,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

After successfully generating the ProgramResource file, now open the file and change the existing code (precisely in the toArray method) to be like the code above.

Each resource class defines a toArray method that returns an array attribute that must be converted to JSON when the resource is returned as a response from a route or controller. We can access the model properties directly from the $this variable. This is because the resource class will automatically proxy property and method access to the underlying model for easy access. Once a resource is defined, it can be returned from a route or controller.

Step 4: Create Controller

 php artisan make:controller API/ProgramController

Then we need to create a new controller to create CRUD logic with Sanctum's REST API. Run the artisan command as above to create a ProgramController.php file in the app/Http/Controllers/API directory.

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;
use App\Models\Program;
use App\Http\Resources\ProgramResource;

class ProgramController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Program::latest()->get();
        return response()->json([ProgramResource::collection($data), 'Programs fetched.']);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required|string|max:255',
            'desc' => 'required'
        ]);

        if($validator->fails()){
            return response()->json($validator->errors());       
        }

        $program = Program::create([
            'name' => $request->name,
            'desc' => $request->desc
         ]);
        
        return response()->json(['Program created successfully.', new ProgramResource($program)]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $program = Program::find($id);
        if (is_null($program)) {
            return response()->json('Data not found', 404); 
        }
        return response()->json([new ProgramResource($program)]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Program $program)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required|string|max:255',
            'desc' => 'required'
        ]);

        if($validator->fails()){
            return response()->json($validator->errors());       
        }

        $program->name = $request->name;
        $program->desc = $request->desc;
        $program->save();
        
        return response()->json(['Program updated successfully.', new ProgramResource($program)]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Program $program)
    {
        $program->delete();

        return response()->json('Program deleted successfully');
    }
}

After successfully generating the ProgramController.php file, now open the controller file and change the existing code to be like the code above. In this ProgramController.php file, we create index, store, update, show and destroy methods.

A brief explanation of the four methods:

  • Index, this method is used to create logic to display all data from table programs.
  • Store, this method is used to add data from the request to the programs table. This method is also equipped with data validation.
  • Show, serves to display detailed program data based on id.
  • Update, serves to receive request data and update program data (based on id) with new request data.
  • Delete, this method serves to delete program data based on the data id sent.

Step 5: Create REST API Routes

 Route::resource('programs', App\Http\Controllers\API\ProgramController::class);

Next, add a new route as above for CRUD program with REST API sanctum in laravel 8. Add that code inside route::group which is protected by middleware or inline with Route::post('/logout').

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

//API route for register new user
Route::post('/register', [App\Http\Controllers\API\AuthController::class, 'register']);
//API route for login user
Route::post('/login', [App\Http\Controllers\API\AuthController::class, 'login']);

//Protecting Routes
Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::get('/profile', function(Request $request) {
        return auth()->user();
    });

    Route::resource('programs', App\Http\Controllers\API\ProgramController::class);

    // API route for logout user
    Route::post('/logout', [App\Http\Controllers\API\AuthController::class, 'logout']);
});

So overall, the code in routes/api.php is now as above.

Step 6: Testing

Okay, after going through the steps starting from adding the sanctum middleware to step 5 which is adding a REST API route, now is the time to test or test the REST API CRUD that we have created with the sanctum package in laravel 8. In this test, we will try to create data, show data, update data, delete data and display all program data using Postman.

Create Data with Sanctum API

Set authorization token

The first test, we will create data or add program data using Postman. But before doing so, make sure you are logged in and get the token. Then in the initial step, we set the authorization token by opening the Authorization tab, selecting the Bearer Token type and then entering the token obtained after successful login.

*Login guide is in the article; Laravel 8: REST API Authentication with Sanctum

Laravel 8 Sanctum Rest API: Create Data

If the authorization token has been set up, now make a POST request to 127.0.0.1:8000/api/programs, then in the body, add the key name and desc along with the values.

If you have added the key and value, continue by clicking the Send button. So as a result, if the entered value is successfully validated, the data will be added to the programs table in the database and will return the response as shown above.

Fetch All Data

Laravel 8 Sanctum REST API: Fetch all data

Then we will try to fetch all data or display all data in the programs table. To do this test, make a GET request to 127.0.0.1:8000/api/programs then click the Send button, then the response results displayed will be like the picture above.

Get Single Data

Laravel 8 Sanctum REST API: Get Single Data

In the third test, we will test or try to get single data or display program details based on id. To do this test, make a GET request to 127.0.0.1:8000/api/programs/{id}, then click the Send button, then the response results displayed will be like the picture above or will display the details of the selected data id.

Update Data

Laravel 8 Sanctum REST API: Update Data

Next we will try to update program data or update data based on id. Make a PUT request to 127.0.0.1:8000/api/programs/{id}. Then on the params tab, enter the key and value or data that will replace the current data (on the data id). If the key and value have been filled in, continue by clicking the Send button, then the resulting response will be as shown above.

Delete Data

Laravel 8 Sanctum REST API: Delete Data

The last test, we will try to delete data or delete data with REST API sanctum in laravel 8. To be able to delete data, make a DELETE request to 127.0.0.1:8000/api/programs/{id} then click Send, then the result is data with that id will be removed from the programs table and will display a response message as shown above.

Conclusion

By the end of this article we have both learned how to create a CRUD REST API (Create, Read, Update & Delete) using the sanctum package in larave 8. Important note, before making or sending a request, make sure you have setup an authorization token by inputting token obtained when successfully logged in.

Hopefully this article can be useful, good luck and see you in the next article.👋

Happy Coding 👨‍🚀 👨‍💻 🚀

 

📖 Full Documentation: Laravel Resources

Tinggalkan Komentar
Loading Comments