Last time we set up our Laravel application and refactored things away from the default so that we could work easier. This time we will dive head first into building our API endpoints. We discussed before the endpoints that we will need, so we will start with those - specifically the ones around events, which is the crux of our focus. To remind you, I will drop them below:
GET /events - Get all events for the authenticated user.
GET /events/{eventId} - Get the details for a specific event.
PATCH /events/{eventId} - Update any details for a specific event.
DELETE /events/{eventId} - Delete an event.
We will want to perform full CRUD functionality on our Event model for easy management. For me, it is always easiest to start with the GET
endpoints that are read operations - as the write operations always require more thought. Let's start with the endpoint to get all events for the authenticated user.
Route::middleware([
'auth:sanctum'
])->prefix('events')->as('events:')->group(
base_path('routes/api/events.php'),
);
I always start by adding the main route group in my routes/api/routes.php
file, which is where I list all of my route groups for my API. By splitting each group of endpoints into separate named files I am never overwhelmed by the amount of routes I have to focus on. We have all been there right? We open the singular routes file for a large application, and have to go make a coffee to calm down because we are overloaded straight away.
Let’s start adding the routes for the events next, in the events.php
file we create.
Route::get('/')->name('index');
Route::post('/')->name('store');
Route::get('{ulid}')->name('show');
Route::put('{ulid}')->name('update');
Route::delete('{ulid}')->name('delete');
I start by scaffolding out the routes I need, as leaving it like this won’t actually break my application. From here I can create the controllers and connect it all together - testing as I go. Now I don’t actually use artisan to create my controllers - because I use PhpStorm and have my templates for things set up to make things easier. However you can use artisan to generate your controllers by using:
php artisan make:controller Api/Events/IndexController -invokable
Typically I found that after I did this, I also had to clean it up to use strict types and final classes, and not to extend the default Controller etc … So it worked out easier for me just to create the PHP class myself in PhpStorm.
final class IndexController
{
public function __invoke(Request $request)
{
}
}
From this point I can start to use my own logic to fetch all of the events for the authenticated user. Let’s walk through how I might do this.
Keep reading with a 7-day free trial
Subscribe to JustSteveKing to keep reading this post and get 7 days of free access to the full post archives.