2
votes

I am having an issue with laravel doing my backend Api. What I am trying to do is return logged user data with Auth::user(); I wrote the controller, the route for the controller method in api.php but when I try to go to the /api/route I am redirected to Home.

I also tried to remove the __construct() method from the controller, When I do this and try to go to the /api/route, dd($user) is returning null.

My controller:

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Http\Resources\TeacherResource;
use Illuminate\Support\Facades\Auth;

class teacherApiController extends Controller
{

    public function __construct(){
        $this->middleware('auth');
    }


    public function information(){
        $user = Auth::user();
        dd($user);
    }
}

Api.php

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

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('information', 'API\teacherApiController@information');

Anything I am doing wrong? I am using the laravel authentication for register and login users.

1

1 Answers

0
votes

I suppose you are not authenticated before calling this route that's why when the __construct was there it redirected you to the home, that's also why Auth::user() returns you null. You are probably not authenticated before calling this route.

To manage the authentication you used laravel passport or even used JWT