Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rei83's avatar
Level 1

Route [login] not defined

Hi everyone, I am new to this forum and first of all I take this opportunity to greet you and thank you for the work you do. I am trying to build a simple rest API using the latest version of Laravel for a quite simple e-learnig platform that I am developing using Reactjs. Everything seemed to be going well when, suddenly, this error appeared: "Route [login] not defined". The strange thing is that if I try to run petitions using Postman app, I can do everything perfectly, however, I get this warning from the browser. I can login without any problems (both through the Postman app and through my React app) and through this I generate the token (which I don't understand why, in the browser doesn't store). I really can't understand what I'm wrong with. Could any of you help me solve these problems? Thanks in advance to anyone who will help me

Best regards,

Alessandro

P.S. I don't know if you allow it here but if you want, I could attach some captures of my code that can allow you to see and understand the problems more directly.

P.P.S. Sorry for my bad english, I'm italian.

0 likes
8 replies
rei83's avatar
Level 1

@bobbybouwmann First of all, thanks for your reply and for your time.

this is the content of my "api.php" file:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('/login', 'UserController@login');
Route::post('/register', 'UserController@register');

Route::group(['middleware' => 'auth:api'], function () {
    Route::apiResource('/prices', 'PriceController');
    Route::apiResource('/companies', 'CompanyController');
    Route::apiResource('/students', 'StudentController');
    Route::apiResource('/payments', 'PaymentController');
    Route::apiResource('/specialities', 'SpecialityController');
    Route::apiResource('/courses', 'CourseController');
    Route::apiResource('/teachers', 'TeacherController');
    Route::apiResource('/posts', 'PostController');
    Route::apiResource('/lessons', 'LessonController');
});

This is, instead, the code for one of my Controllers:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();
        return response()->json([
            "data" => $posts,
            "status" => Response::HTTP_OK
        ], Response::HTTP_OK);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $post = Post::create($request->all());
        return response()->json([
            "message" => "Il post è stato creato correttamente",
            "data" => $post,
            "status" => Response::HTTP_CREATED,
        ], Response::HTTP_CREATED);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        return response()->json([
            "data" => $post,
            "status" => Response::HTTP_OK,
        ], Response::HTTP_OK);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $post->update($request->all());
        return response()->json([
            "message" => "Il post è stato aggiornato correttamente",
            "data" => $post,
            "status" => Response::HTTP_OK,
        ], Response::HTTP_OK);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();
        return response()->json([
            "message" => "Il post è stato eliminato correttamente",
            "data" => $post,
            "status" => Response::HTTP_OK,
        ], Response::HTTP_OK);
    }
}

These, instead, are the links for the captures of all of my routes (obtained by doing "php artisan serve":

link link link

If necessary, I could attach more code to better understand the problems, thanks again.

Alessandro

Snapey's avatar

This is the error handler for when you try to access a protected route and are not logged in.

The framework throws an exception, then the handler catches it and sends you to the 'login' route

vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
                    ? response()->json(['message' => $exception->getMessage()], 401)
                    : redirect()->guest($exception->redirectTo() ?? route('login'));
    }

so its mandatory that you have a route named login in web.php, even if its only to an error page

alternatively, create a method called redirectTo() in app\Exceptions\Handler.php which returns the place you want the user to be sent when they are not logged in and access a route protected by auth middleware.

rei83's avatar
Level 1

@snapey Thank you too for your answer, I think I did what you suggested but the problem persists. This is the code for my "Handler.php" file:

<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Response;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        if ($request->wantsJson()) {
            if ($exception instanceof ModelNotFoundException)
            {
                return response()->json([
                    "message" => "Il dato sollecitato non è stato trovato",
                    "status" => Response::HTTP_NOT_FOUND
                ], Response::HTTP_NOT_FOUND);
            }

            return response()->json(["error" => "Qualcosa è andato storto..."], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
        return parent::render($request, $exception);
    }
}

Did I do something wrong?

Snapey's avatar

Where is your redirectTo method?

rei83's avatar
Level 1

@snapey now i tried to apply the redirectTo () method in Handler.php but unfortunately the problem persists. Take a look:

<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Response;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        if ($request->wantsJson()) {
            if ($exception instanceof ModelNotFoundException)
            {
                return response()->json([
                    "message" => "Il dato sollecitato non è stato trovato",
                    "status" => Response::HTTP_NOT_FOUND
                ], Response::HTTP_NOT_FOUND);
            }

            return response()->json(["error" => "Qualcosa è andato storto..."], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
        return parent::render($request, $exception);

    }




    protected function redirectTo($request)
    {
        return route($request->path . '/prices');
    }

}
iajohn's avatar

@rei83 there is nothing wrong with your code in the Handler.php, but I think what @snapey was saying is that you can solve the Route [login] not define error by creating a method called redirectTo() in app\Exceptions\Handler.php to redirect users that are not logged in to a view page that is not protected by middleware e.g landing page of your app for guest users.

The redirectTo() can look like this

protected function redirectTo()
{
  if (Auth::check()) { // this line will check if the user has been authenticated
    return '/protectedPageWithAuthMiddleware';  // this line should redirect user to a page that is protected with auth middleware e.g. Dashboard 
  } else {
    return '/landingPageWithoutAuthMiddleware'; // this line should redirect user without authentication to a page that is not protected by auth middleware 
  }
}
Snapey's avatar

is prices also protected by auth middleware?

What are users supposed to do if routes are protected but there is no login page?

Please or to participate in this conversation.