An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
Laravel 8 - API Resources for Beginners
What does API Resources mean?
Acts as a transformation layer that sits between our Eloquent models and the JSON responses that are actually returned by our API.
**API resources **present a way to easily transform our models into JSON responses
.
Sample commands for creating the resource class and resource collection using php artisan
// create a resource class $ php artisan make:resource UserResource // create a resource collection using either of the two commands $ php artisan make:resource Users --collection $ php artisan make:resource UserCollection
This is the representation of the database api we are gonna create.
Lets start by creating a new laravel app
$ laravel new book-reviws-api
Create models and migrations
The book reviews API will have three models: User, Book and Rating.
Well start by creating the Book
model:$ php artisan make:model Book -m
Next, lets open the migration file generated for the Book model and update the up() method as below:
database/migrations/TIMESTAMP_create_books_table.php
public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); }
Well do the same for the Rating
model:$ php artisan make:model Rating -m
Open the migration file generated for the Rating model and update the up() method as below:
database/migrations/TIMESTAMP_create_ratings_table.php
public function up() { Schema::create('ratings', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->unsignedInteger('book_id'); $table->unsignedInteger('rating'); $table->timestamps(); }); }
Run the the command below to run the migrations:$ php artisan migrate
Remember to enter your database details in the .env
file before running the command above.
Define relationships between models
A user can add as many books as they wish, but a book can only belong to one user. So, the relationship between the User model and Book model is a
one-to-many
relationship.
Lets define that. Add the code below inside the User model:
app/User.php
public function books() { return $this->hasMany(Book::class); }
Next, lets define the inverse relationship on the Book model:
app/Book.php
public function user() { return $this->belongsTo(User::class); }
Likewise, a book can be rated by various users, hence a book can have many ratings. A rating can only belong to one book. This is also a
one-to-many
relationship.
Add the code below in the Book model:
app/Book.php
public function ratings() { return $this->hasMany(Rating::class); }
Then we define the inverse relationship inside the Rating model:
app/Rating.php
public function book() { return $this->belongsTo(Book::class); }
Allowing mass assignment on some fields
To avoid getting the mass assignment error which Laravel will throw by default, we need to specify the columns we want to be mass assigned.
Lets add the snippet below to our models respectively:
app/Book.php
protected $fillable = ['user_id', 'title', 'description'];
app/Rating.php
protected $fillable = ['book_id', 'user_id', 'rating'];
Defining API routes
Lets define our routes. Open routes/api.php
and add the line below to it:
Route::apiResource('books', 'BookController'); Route::post('books/{book}/ratings', 'RatingController@store');
Since we are building an API, we make use of apiResource()
to generate API only routes.
Also, we define a route that will be used to rate a specified book. For instance, /books/53/ratings
will be used to rate the book with the ID of 53
.
Note:
When building APIs with Laravel, it is recommended to use theapiResource()
method while defining resourceful routes, this will generate only API specific routes (index
,store
,show
,update
anddestroy
). Unlike when you use theresource()
method, which will in addition to generating API specific routes, also generatecreate
andedit
routes, which arent needed when building an API.
Creating the book resource
Before we move on to create theBooksController
, lets create a book resource class. Well make use of the artisan command make:resource
to generate a new book resource class. By default, resources will be placed in the app/Http/Resources
directory of our application.
$ php artisan make:resource BookResource
Once that is created, lets open it and update the toArray()
method as below:
app/Http/Resources/BookResource.php
public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'description' => $this->description, 'created_at' => (string) $this->created_at, 'updated_at' => (string) $this->updated_at, 'user' => $this->user, 'ratings' => $this->ratings, ]; }
As the name suggests, this will transform the resource into an array.
We can access the model properties directly from the $this
variable.
Now we can make use of the BookResource
class in our controller.
Creating the book controller
Lets create the BookController
. For this, well make use of the API controller generation feature $ php artisan make:controller BookController --api
Next, open it up and paste the following code into it:
app/Http/Controllers/BookController.php
use App\Book; use App\Http\Resources\BookResource;// ... public function index() { return BookResource::collection(Book::with('ratings')->paginate(25)); } public function store(Request $request) { $book = Book::create([ 'user_id' => $request->user()->id, 'title' => $request->title, 'description' => $request->description, ]); return new BookResource($book); } public function show(Book $book) { return new BookResource($book); } public function update(Request $request, Book $book) { // check if currently authenticated user is the owner of the book if ($request->user()->id !== $book->user_id) { return response()->json(['error' => 'You can only edit your own books.'], 403); } $book->update($request->only(['title', 'description'])); return new BookResource($book); } public function destroy(Book $book) { $book->delete(); return response()->json(null, 204); }
Original Link: https://dev.to/dalelantowork/laravel-8-api-resources-for-beginners-2cpa
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To