Laravel API Resource Links

News

October 10th, 2019

laravel-resource-links.png

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:

1class UserResource extends JsonResource
2{
3 use Spatie\ResourceLinks\HasLinks;
4 use Spatie\ResourceLinks\HasMeta;
5 
6 public function toArray($request): array
7 {
8 return [
9 'id' => $this->id,
10 'name' => $this->name,
11 'links' => $this->links(UsersController::class),
12 ];
13 }
14 
15 public static function meta()
16 {
17 return [
18 'links' => self::collectionLinks(UsersController::class),
19 ];
20 }
21}

The above code will generate the following:

1{
2 "data":[
3 {
4 "id":1,
5 "name": "Ruben Van Assche",
6 "links": {
7 "show": "https://laravel.app/users/1",
8 "edit": "https://laravel.app/users/1/edit",
9 "update": "https://laravel.app/users/1",
10 "delete": "https://laravel.app/users/1"
11 }
12 }
13 ],
14 "meta": {
15 "links": {
16 "index": "https://laravel.app/users",
17 "create": "https://laravel.app/users/create",
18 "store": "https://laravel.app/users"
19 }
20 }
21}

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.