Skip to content

Commit f6b5ae7

Browse files
authored
Merge pull request #9 from huntie/documentation
Current progress on documentation
2 parents b18e1ff + 2be3e90 commit f6b5ae7

File tree

2 files changed

+217
-3
lines changed

2 files changed

+217
-3
lines changed

README.md

Lines changed: 216 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,223 @@ An implementation of the [JSON API](http://jsonapi.org/) specification for Larav
1111
1212
## Installation
1313

14-
Install the latest pre-release using [Composer](https://getcomposer.org/):
14+
1. Install the latest pre-release using [Composer](https://getcomposer.org/).
1515

16-
$ composer require huntie/laravel-simple-jsonapi
16+
$ composer require huntie/laravel-simple-jsonapi
17+
18+
2. Add a reference to `JsonApiServiceProvider` under the `providers` array in `config/app.php`.
19+
20+
```php
21+
Huntie\JsonApi\JsonApiServiceProvider::class
22+
```
23+
24+
3. Run the following Artisan command to publish a local configuration file at `config/jsonapi.php`.
25+
26+
$ php artisan vendor:publish
27+
28+
## JsonApiController
29+
30+
The main class in this package is `JsonApiController`, which provides a full set of create, read, update and delete actions for a given Eloquent Model. A bunch of query parameters are supported which will affect the JSON API Objects returned, and you can also fetch and update model relationships.
31+
32+
### Basic usage
33+
34+
#### 1. Define routes
35+
36+
Add a [RESTful resource route](https://laravel.com/docs/5.2/controllers#restful-resource-controllers) for the target model in `routes.php`.
37+
38+
```php
39+
Route::resource('users', 'UserController');
40+
```
41+
42+
Using the `'only'` key here allows you to enable a only subset of resource endpoints before they hit the controller:
43+
44+
```php
45+
Route::resource('users', 'UserController', [
46+
'only' => ['index', 'show', 'update'],
47+
]);
48+
```
49+
50+
#### 2. Add controller
51+
52+
Our new controller for this resource needs to extend `JsonApiController` and use the `JsonApiControllerActions` trait. The base information to provide is the type of `Model` this controller is for, by implementing the abstract method `getModel`.
53+
54+
```php
55+
<?php
56+
57+
namespace App\Http\Controllers;
58+
59+
use App\User;
60+
use Huntie\JsonApi\Http\Controllers\JsonApiController;
61+
use Huntie\JsonApi\Http\Controllers\JsonApiControllerActions;
62+
63+
class UserController extends JsonApiController
64+
{
65+
use JsonApiControllerActions;
66+
67+
/**
68+
* Return the related Eloquent Model.
69+
*
70+
* @return Model
71+
*/
72+
protected function getModel()
73+
{
74+
return new User();
75+
}
76+
}
77+
```
78+
79+
The trait `JsonApiControllerActions` is important. It defines each endpoint `index`, `store`, `show`, `update`, `destroy` at the class level and calls the relevant parent controller method, e.g. `indexAction`. This allows us to override particular controller actions, meaning we can specify additional parameters as well as a different type-hinted request class for [Form Request Validation](https://laravel.com/docs/5.2/validation#form-request-validation).
80+
81+
The controller now will respond to each endpoint for this resource where a route has been defined.
82+
83+
#### Implicit model transformation
84+
85+
Whenever a model is tranformed into a JSON API Object or Collection, the built-in properties and methods defined on your Eloquent Model, such as `$casts`, `$hidden`, and `$appends` will apply automatically, removing the need for separate model tranformation logic. See [the Laravel docs](https://laravel.com/docs/5.2/eloquent) for more information on what is available.
86+
87+
This package uses these Eloquent features heavily – the examples demonstrate further how these are applied.
88+
89+
## Examples
90+
91+
Coming soon.
92+
93+
## Errors
94+
95+
There are a number of contexts where you may return error responses as formatted JSON API Error Objects.
96+
97+
### Form validation
98+
99+
Implementing a [Form Request validation class](https://laravel.com/docs/5.2/validation#form-request-validation) that extends `JsonApiRequest` will format any validation errors appropriately when a validation error occurs.
100+
101+
```php
102+
<?php
103+
104+
namespace App\Http\Requests\User;
105+
106+
use Auth;
107+
use Huntie\JsonApi\Http\Requests\JsonApiRequest;
108+
109+
class UpdateUserRequest extends JsonApiRequest
110+
{
111+
/**
112+
* Determine if the user is authorized to make this request.
113+
*
114+
* @return bool
115+
*/
116+
public function authorize()
117+
{
118+
return $this->route('user')->id === Auth::id();
119+
}
120+
121+
/**
122+
* Get the validation rules that apply to the request.
123+
*
124+
* @return array
125+
*/
126+
public function rules()
127+
{
128+
return [
129+
'data.type' => 'required|in:users',
130+
'data.attributes.name' => 'required|max:255',
131+
'data.attributes.email' => 'required|email|unique:users,email',
132+
'data.attributes.password' => 'required|min:6',
133+
];
134+
}
135+
}
136+
```
137+
138+
The validation rules are applied by type-hinting the request class in your controller method and then calling the associated parent action.
139+
140+
```php
141+
/**
142+
* Update a specified user.
143+
*
144+
* @param UpdateUserRequest $request
145+
* @param User $user
146+
*
147+
* @return JsonApiResponse
148+
*/
149+
public function update(UpdateUserRequest $request, User $user)
150+
{
151+
return $this->updateAction($request, $user);
152+
}
153+
```
154+
155+
A subsequent POST request to `/users/{user}` with multiple validation errors will return a validation error response with pointers to each invalid attribute.
156+
157+
HTTP/1.1 422 Unprocessable Entity
158+
Content-Type: application/vnd.api+json
159+
160+
```json
161+
{
162+
"errors": [
163+
{
164+
"source": { "pointer": "data/attributes/name" },
165+
"title": "Invalid attribute",
166+
"detail": "The name field is required."
167+
},
168+
{
169+
"source": { "pointer": "data/attributes/password" },
170+
"title": "Invalid attribute",
171+
"detail": "The password must be at least 6 characters."
172+
}
173+
]
174+
}
175+
```
176+
177+
### JsonApiErrors trait
178+
179+
The `JsonApiErrors` trait is a convenient helper for returning JSON API error responses following any request.
180+
181+
```php
182+
<?php
183+
184+
namespace App\Http\Middleware;
185+
186+
use Closure;
187+
use Huntie\JsonApi\Support\JsonApiErrors;
188+
use Illuminate\Http\Request;
189+
use Illuminate\Http\Response;
190+
191+
class Authenticate
192+
{
193+
use JsonApiErrors;
194+
195+
/**
196+
* Handle an incoming request.
197+
*
198+
* @param Request $request
199+
* @param Closure $next
200+
*
201+
* @return mixed
202+
*/
203+
public function handle(Request $request, Closure $next)
204+
{
205+
if (!$request->headers->get('Authorization')) {
206+
return $this->error(Reponse::HTTP_BAD_REQUEST, 'No token provided');
207+
}
208+
209+
// Further logic
210+
211+
return $next($request);
212+
}
213+
}
214+
```
215+
216+
Invalid requests to routes with this middleware will return a formatted error object. Optionally, a third parameter can be provided to `error()`, which will add a `"detail"` value.
217+
218+
HTTP/1.1 400 Bad Request
219+
Content-Type: application/vnd.api+json
220+
221+
```json
222+
{
223+
"errors": [
224+
{
225+
"status": "400",
226+
"title": "No token provided"
227+
}
228+
]
229+
}
230+
```
17231

18232
## Contributing
19233

src/Http/Controllers/JsonApiController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ protected function getModelType()
4141
/**
4242
* The model relationships that can be updated.
4343
*
44-
* @return string
44+
* @return array
4545
*/
4646
protected function getModelRelationships()
4747
{

0 commit comments

Comments
 (0)