before we start, you should have some basic knowledge and understanding of the PHP and laravel framework. hope you have, let’s start.

Prerequisites

  • PHP 7.2 or Higher
  • Composer
  • MySql
  • Laravel 6 or Higher
  • Postman (Testing Rest APIs)

We assume you already have installed and configured laravel with database and migration, its up and running, if it’s not then you can follow our laravel installation tutorial.

we will create a controller that will contain the methods for our API by running below command:

Open the terminal

php artisan make:controller UserApiController

A new file will be created named UserApiController.php in the app\http\controllers directory. Next, we will add the following methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserApiController extends Controller
{
    public function getAllUsers() {
      // logic to get all users goes here
    }

    public function createUser(Request $request) {
      // logic to create a user record goes here
    }

    public function getUser($id) {
      // logic to get a user record goes here
    }

    public function updateUser(Request $request, $id) {
      // logic to update a user record goes here
    }

    public function deleteUser ($id) {
      // logic to delete a user record goes here
    }
}

Next, proceed to the routes directory and open the api.php file and create the endpoints that will reference to the methods created earlier in the UserApiController.

Route::get('users', 'ApiController@getAllUsers');

Route::get('user/{id}', 'ApiController@getUser');

Route::post('user, 'ApiController@createUser');

Route::put('user/{id}', 'ApiController@updateUser');

Route::delete('user/{id}','ApiController@deleteUser');

Note: All routes in api.php are prefixed with /api by default, so we will call it like /api/users

Create a User

Locate the createUser method in our UserApiController

public function createUser(Request $request) {
  // logic to create a user record goes here
}

include the User Class in the UserApiController controller.

<?php

use App\User;

class UserApiController extends Controller
{
  ...
}

Now, we will get the request parameters in the $request object injected in the createUser method and store it into the database with User Class Model.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserApiController extends Controller
{
  ...
  public function createUser(Request $request) {
    $user = new User;
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = bycrpt($request->password);
    $user->save();

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

Test

Now, we will test this endpoint, before testing make sure your application is running. You can use below command:

php artisan serve

Open Postman and make a POST request to http://localhost:8000/api/users. Select the form-data option and pass the following values as seen in the image below:

IMAGE GOES HERE

It works if it returns success message along with the 201 response code. Try adding a few more records to populate our database for the next task.

Get all users

Now let us visit the getAllUsers method in our UserApiController

public function getAllUsers() {
  // logic to get all users goes here
}

We will use the already imported User model to make a simple eloquent query to return all users from the database.

class UserApiController extends Controller
{
  public function getAllUsers() {
    $users = User::get()->toJson();
    return response($users, 200);
  }
  ...
}

This method is already linked to the api/users route.

Testing

Assume our application is already running. Make a GET request to the /api/users endpoint in Postman.

IMAGES GOES HERE

Open the Postman and make a GET request to the /api/users endpoint. You will see all the users.

Get a user record

Locate the getUser method in the UserApiController

public function getUser($id) {
  // logic to get a user record goes here
}

Now, We will create a endpoint to retrieve specific user record by passing user id in the /api/user/{id} endpoint.

...
class ApiController extends Controller
{
  ...
  public function getUser($id) {

      $user = User::where('id', $id)->first()->toJson();
      if ($user) {
        return response($user, 200);
      } else {
        return response()->json([
          "message" => "User not found"
        ], 404);
      }
      
  }
  ...
}

Open the Postman and make a GET request to the /api/user/{id} endpoint {id} can be the id of an existing record you may have in your database.You will see all the users.

IMAGES GOES HERE

Update a user record

Now let us visit the updateUser method in our UserApiController

public function updateUser(Request $request, $id) {
   // logic to update a user record goes here
}

Now, we will check it first if the record we are trying to update exists. if it does it will update the records against the matched id and return status code 200.If it does not exist, it will return a message indicating that the record was not found along with 404 status code.

public function updateUser(Request $request, $id) {
    
    if (User::where('id', $id)->exists()) {
        $user = User::find($id);
        $user->name = is_null($request->name) ? $user->name : $request->name;
        $user->save();

        return response()->json([
            "message" => "record updated successfully"
        ], 200);

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

Testing

To test it we retrieve specific user record by passing user id 1 in the previously defined GET endpoit. /api/user/1.

Now, we will change the user name to “Nisar Ahmed” by making PATCH request api/user/1.

you have to pass a JSON payload via form-data to make PATCH request.

Delete a User Record

Now let us visit the deleteUser method in our UserApiController.

public function userUser(Request $request, $id) {
   // logic to update a user record goes here
}

Now, We will create a endpoint to delete specific user record by making a DELETE request to the /api/user/{id}endpoint.


public function deleteUser ($id) {
if(User::where(‘id’, $id)->exists()) {
$user = User::find($id);
$user->delete();

public function deleteUser ($id) {
      if(User::where('id', $id)->exists()) {
        $user = User::find($id);
        $user->delete();

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

This method is already linked to the api/user/{$id}route.

Author

I am a Laravel developer with some other skills.

Write A Comment