M. Badovsky M. Badovsky - 1 month ago 8
PHP Question

Laravel refer to application url when no logged

I've routing file below

Route::group(['middleware' => ['auth:web', 'web'], 'prefix' => 'api/1.0'], function () {

Route::get('dashboard', 'DashboardController@index');
Route::get('site/{id}', 'SiteController@index');

});


When I'm not logged, and trying to refer to url http://app.url/api/1.0/, is return login panel. How can I set instead login panel, return json data(for example[ message: forbidden]). Im was trying in middleware settings but laraver was crashed. Thank you

Answer

You can use auth:api middleware for this as:

Route::group(['middleware' => ['auth:api'],  'prefix' => 'api/1.0'], function () {

    Route::get('dashboard',  'DashboardController@index');
    Route::get('site/{id}', 'SiteController@index');

});

Update

All exceptions are handled by the App\Exceptions\Handler class. You can edit the render() fuction of this class to return JSON response as:

public function render($request, Exception $exception)
{
    if ($request->is('api/*');) {
        return $this->renderRestException($request, $exception);
    }

    return parent::render($request, $exception);
}

Add two functions in the same file as:

/**
 * Render an exception into a response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\JsonResponse
 */
public function renderRestException(Request $request, Exception $e)
{
    switch($e)
    {
        case ($e instanceof HttpResponseException):
            return response()->json($e->getResponse()->getContent(), $e->getResponse()->getStatusCode());

        case ($e instanceof ModelNotFoundException):
            return response()->json($e->getMessage(), 404);

        case ($e instanceof AuthenticationException):
            return response()->json('Unauthorized', 401);

        case ($e instanceof AuthorizationException):
            return response()->json($e->getMessage(), 403);

        default:
            return $this->convertExceptionToJsonResponse($e);
    }
}

/**
 * Create a Symfony response for the given exception.
 *
 * @param  \Exception  $e
 * @return \Illuminate\Http\JsonResponse
 */
protected function convertExceptionToJsonResponse(Exception $e)
{
    $e = FlattenException::create($e);

    return response()->json(array_get(SymfonyResponse::$statusTexts, $e->getStatusCode()), $e->getStatusCode());
}

Remember to import all these classes at the top of the class:

use Exception;
use Illuminate\Http\Request;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Exception\HttpResponseException;
use Symfony\Component\Debug\Exception\FlattenException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
Comments