Laravel API Resource Links

News

October 10th, 2019

Laravel API Resource Links

Laravel Resource Links is a package by Ruben Van Assche and Spatie that adds links to your Laravel API resources without a hassle.

Here’s one example from the package’s documentation that illustrates a typical UserResource matching a Laravel Resource Controllers:

class UserResource extends JsonResource
{
use Spatie\ResourceLinks\HasLinks;
use Spatie\ResourceLinks\HasMeta;
 
public function toArray($request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'links' => $this->links(UsersController::class),
];
}
 
public static function meta()
{
return [
'links' => self::collectionLinks(UsersController::class),
];
}
}

The above code will generate the following:

{
"data":[
{
"id":1,
"name": "Ruben Van Assche",
"links": {
"show": "https://laravel.app/users/1",
"edit": "https://laravel.app/users/1/edit",
"update": "https://laravel.app/users/1",
"delete": "https://laravel.app/users/1"
}
}
],
"meta": {
"links": {
"index": "https://laravel.app/users",
"create": "https://laravel.app/users/create",
"store": "https://laravel.app/users"
}
}
}

Now your frontend has everything necessary to navigate the API for a given user. Providing collection meta also provides access to links for listing existing users and creating new users.

The laravel-resource-links documentation is an excellent place to start learning more about this package. You can also view the source code on GitHub at spatie/laravel-resource-links.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.