Courses

Laravel Travel Agency API From Scratch

As we have our Admin users created with the Artisan command, we can log in and create Travel records.

Task Description from Client is extremely simple: "A private (admin) endpoint to create new travels".

I'm a fan of doing things in this order:

  1. Create the endpoint without Auth
  2. Only then protect it with Middleware

So this is precisely the plan.


Controller / Route / Request

We generate the Controller:

php artisan make:controller Api/V1/Admin/TravelController

In addition to previously used Api/V1 prefixes, I added the third one, /Admin, to separate the Controllers for administrators.

Then, in the Routes, we add this:

routes/api.php:

use App\Http\Controllers\Api\V1\Admin;
 
// ...
 
Route::get('travels', [TravelController::class, 'index']);
Route::get('travels/{travel:slug}/tours', [TourController::class, 'index']);
 
Route::prefix('admin')->group(function () {
Route::post('travels', [Admin\TravelController::class, 'store']);
});

As you can see, now we have two Controllers with the same name of TravelController, just in different namespaces, so be careful which one you use in the Routes.

Did you know you can import use XXXXX as the entire namespace and then use it as a prefix for the route itself, like Admin\TravelController in my example above?

Alternatively, you can name those Controllers differently for clarity.

Next, let's generate a Form Request class for...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 66 courses (1167 lessons, 43 h 18 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord