How to create API in Laravel 8?

how to create api in laravel

If you want to create an API using a resource controller in Laravel, you can follow these steps:

1. Create a new Laravel project: If you haven’t already created a Laravel project, you can use Composer to create one. Open your command line and run the following command:

composer create-project --prefer-dist laravel/laravel api-project

2. Set up your database: Configure your database connection details in the .env file located in the root of your Laravel project.

3. Create a route: Open the routes/api.php file and define the route for your resource controller. You can use the Route::resource method to generate the necessary routes. For example:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::resource('users', UserController::class);

4. Generate the resource controller: Run the following command to generate a resource controller for your API:

php artisan make:controller UserController --resource

5. Implement the resource methods: Open the generated UserController file in the app/Http/Controllers directory. It will contain the necessary methods for CRUD operations. You can modify these methods as per your requirements. For example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Hash;
class UserController extends Controller
{

    protected $response;

    // The Response is variable to hold the structure for response.
    // I suggest to create trait for response which is best practice, this is the
    // just for understanding.

    public function __construct() {

        $this->response = [
            'status'    => 0,
            'success'    => false,
            'message'   => '',
            'data'      => []
        ];
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        // do not forgot to skip exception handling..

        try {

            $users = User::get();

            $this->response['status'] = 200;
            $this->response['success'] = true;
            $this->response['message'] = 'Record fetched successfuly!';
            $this->response['data'] = $users;

            return response()->json($this->response, 200);

        } catch (\Throwable $th) {

            $this->response['status'] = 500;
            $this->response['success'] = false;
            $this->response['message'] = 'Something went wrong!';
            $this->response['data'] = null;

            return response()->json($this->response, 500);
        }

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        try {
            //code...
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        try {


            $validator = $request->validate([
                'name'      => 'required',
                'email'     => 'required|email|unique:users,email',
                'password'  => 'min:6|required_with:password_confirmation|same:password_confirmation'
            ]);

            if ($validator->fails()) {

                $this->response['status'] = 490;
                $this->response['success'] = true;
                $this->response['message'] = 'validation failed';
                $this->response['data'] = null;

                return response()->json($this->response, 490);
            }

            $user = User::create([
                'name'  => $request->name,
                'email'  => $request->email,
                'password'  => Hash::make($request->password),
            ]);


            $this->response['status'] = 200;
            $this->response['success'] = true;
            $this->response['message'] = 'User created successfuly!';
            $this->response['data'] = $user;

            return response()->json($this->response, 200);

        } catch (\Throwable $th) {

            $this->response['status'] = 500;
            $this->response['success'] = false;
            $this->response['message'] = 'Something went wrong!';
            $this->response['data'] = null;

            return response()->json($this->response, 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //

        try {

            $user = User::findOrFail($id);

            if($user) {

                $this->response['status'] = 200;
                $this->response['success'] = true;
                $this->response['message'] = 'Record fetched successfuly!';
                $this->response['data'] = $users;

            } else {

                $this->response['status'] = 404;
                $this->response['success'] = true;
                $this->response['message'] = 'Record not found!';
                $this->response['data'] = null;

            }

            return response()->json($this->response, 200);

        } catch (\Throwable $th) {

            $this->response['status'] = 500;
            $this->response['success'] = false;
            $this->response['message'] = 'Something went wrong!';
            $this->response['data'] = null;

            return response()->json($this->response, 500);
        }

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        try {
            //code...
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        try {
            //code...
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        try {
            //code...
        } catch (\Throwable $th) {
            //throw $th;
        }
    }
}

Test your API: You can use tools like Postman or cURL to send HTTP requests to your API endpoints and verify their functionality.

How to create API in Laravel 8?
How to create API in Laravel 8? – Code following

By placing the API routes in the api.php file, Laravel automatically applies API-specific middleware and prefixes the routes with the /api prefix. Make sure to handle validation, authentication, and other requirements specific to your project. You can refer to the Laravel documentation for more details on API development.

Tips:

  1. Use exception handling to manage errors.
  2. use database transactions while storing, updating, delete records from your database.

Reference document from Laravel official documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *