How to Handle "404 route not found" and "405 Method Not Allowed" in Laravel API

How to Handle "404 route not found" and "405 Method Not Allowed" in Laravel API

If u develop Laravel application API's u will face new exceptions when u use postman, like: 404 route not found if u write wrong route, 405 method not allowed if u use anther type of method. so we need to handle Exceptions with better way.

vs api.jpg

1- Install Laravel Application

composer create-project laravel/laravel HandleExceptions

2- Create Trait to return Api Response.
I will create it at App/Http/Traits/apiResponse.php code:

<?php
namespace App\Http\Traits;



trait ApiResponseTrait{

    /**
     * [
     *  code => default 200 and dataType is int.
     *  message => default null and dataType is String.
     *  errors => default null and dataType is Array.
     *  data => default null and dataType id Array
     * ]
     */


    public function apiResponse($code = 200, $message = null, $errors = null, $data = null){

        $array = [
            'status' => $code,
            'message' => $message,

        ];
        if(is_null($data) && !is_null($errors)){
            $array['errors'] = $errors;
        }elseif(is_null($errors) && !is_null($data)){
            $array['data'] = $data;
        }

        return response($array , 200);
    }




}

?>

3- Open App/Exceptions/Handler.php Here we will add function "render" like blew:

public function render($request, Throwable $e)
    {

        if ($e instanceof NotFoundHttpException)
        {
            return $this->apiResponse(404,"error 404", $request->url() . ' Not Found, try with correct url');
        }
        if($e instanceof MethodNotAllowedHttpException)
        {
            return $this->apiResponse(404,"error 405",  $request->method() . ' method Not allow for this route, try with correct method');
        }
    }

Note: don't forget to use ApiResponseTrait

U can look at Repo Code https://github.com/mohamedgouda98/HandleApiExceptions