Laravel REST API — 2. CRUD Operations

Zeba Rahman
fabcoding
Published in
4 min readAug 15, 2020

Assuming you have an existing Laravel project, we will create a database for Books and we will write endpoints for its CRUD operations, which means Create, Read, Update and Delete. We will create the following endpoints:

GET /api/books : to return a list of all the books

GET /api/books/{id} : to return details of a particular book by ID

POST /api/books : to create a new book

PUT /api/books/{id} : to update details of a book by iD

DELETE /api/books/{id} : to delete a book by ID

So let’s get started.

Note: If you don’t have an existing Laravel project, please check this and this.

Step 1

Create the model

First we create the model of the book.

php artisan make:model Book -m

This will generate 2 things — the model php file and the migration for the database table. Let us edit both the files to have all the fields we require.

app/Book.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model {
protected $fillable = [
'name', 'author'
];
}

database/migrations/xxx.xxx_create_books_table.php

Modify the up() function here

...
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('author');
$table->timestamps();
});
}
...

Now run the command

php artisan migrate

Our model and database are ready now.

Step 2

The controller

Now we will create a controller which will hold all the methods for the API. Run the following command to create a controller.

php artisan make:controller Api/BookController

Open the newly created file.

app/Http/Controllers/Api/BookController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;

class BookController extends Controller {

}

Now write functions logic for each of the endpoints.

1. Function to get all the books from the database table.

public function getAllBooks() {
$books = Book::get()->toJson(JSON_PRETTY_PRINT);
return response($books, 200);
}

2. Function to get a particular book by ID

public function getBook($id) {
if (Book::where('id', $id)->exists()) {
$book = Book::where('id', $id)->get()->toJson(JSON_PRETTY_PRINT);
return response($book, 200);
} else {
return response()->json([
"message" => "Book not found"
], 404);
}
}

3. Function to create a new book

public function createBook(Request $request) {
$book = new Book;
$book->name = $request->name;
$book->author = $request->author;
$book->save();

return response()->json([
"message" => "Book record created"
], 201);
}

4. Function to update a book by ID

public function updateBook(Request $request, $id) {
if (Book::where('id', $id)->exists()) {
$book = Book::find($id);

$book->name = is_null($request->name) ? $book->name : $book->name;
$book->author = is_null($request->author) ? $book->author : $book->author;
$book->save();

return response()->json([
"message" => "records updated successfully"
], 200);
} else {
return response()->json([
"message" => "Book not found"
], 404);
}
}

5. Function to delete a book by ID

public function deleteBook ($id) {
if(Book::where('id', $id)->exists()) {
$book = Book::find($id);
$book->delete();

return response()->json([
"message" => "records deleted"
], 202);
} else {
return response()->json([
"message" => "Book not found"
], 404);
}
}

Now that we have written all the logic, let us define routes for these.

Step 3

The routes

Add the routes to the API routes file, to access all the functions we wrote.

routes/api.php

Route::get('books', 'Api\BookController@getAllBooks');
Route::get('books/{id}', 'Api\BookController@getBook');
Route::post('books', 'Api\BookController@createBook');
Route::put('books/{id}', 'Api\BookController@updateBook');
Route::delete('books/{id}','Api\BookController@deleteBook');

Now we are ready to test these.

Test the endpoints

Open postman and test the endpoints.

Prefix the URLs with /api/

Example, for creating a book:

Example for retrieving all books:

Similarly you can test other endpoints.

Step 4

Authenticated requests

Note — If you do not have authentication set up in your project, you can follow this article for that.

Most of the times, you will want to secure your endpoints to that they can only be accessed with a valid access token by a logged-in user. Open the routes file and Simply wrap all the routes in the middleware like this.

routes/api.php

Route::group(['middleware' => 'auth:api'], function() {
//routes here
});

Test again using the access token obtained from authentication. You must add the token in Headers with the key Authorization and the value as Bearer <Your token>.

This way, without authorization, your endpoint cannot be used.

Originally published at Fabcoding.

--

--