2

I'm using Laravel 7 and my problem is to get null from Auth::user(); auth()->user and Auth::id() return null as well.

BTW, in balde template Auth::user() works. It returns null when I try to use it in controller.

What I'm trying to do is to create a comment page in backend (Vuejs) and I want to build up a filter logic. In order to do that, I want to add a new property named repliedBy into each comment in controller. If a comment isn't replied by the current user, repliedBy will be notByMe. So I don't event try to return user id to Vuejs. I can't get id even in the controller. BTW, login, registration etc work normal way.

Here is my CommentsController:

    public function index()
    {
        $comments = Comment::join("site_languages", "language_id", "=", "site_languages.id")
            ->select("content_comments.*", "site_languages.shorthand as lang_shorthand")
            ->with(["replies", "post", "user"])
            ->orderBy('id', 'desc')
            ->get()
            ->groupBy("commentable_type");

        $grouppedComments = [];
        foreach ($comments as $type => $typeSet) {
            $newType = strtolower(explode("\\", $type)[1]);
            $grouppedByLanguage = $typeSet->groupBy("lang_shorthand");
            $langSet = [];
            foreach ($grouppedByLanguage as $lang => $commentSet) {
                $grouppedBycontent = [];
                foreach ($commentSet as $comments) {
                    $content = $newType . "_" . $comments->commentable_id;
                    if (array_key_exists($content, $grouppedBycontent)) {
                        array_push($grouppedBycontent[$content], $comments);
                    } else {
                        $grouppedBycontent[$content] = [$comments];
                    }
                }
                $groupAfterOrganized = [];
                foreach ($grouppedBycontent as $content => $comments) {
                    $order = 1;
                    $commentAndReplies = [];
                    foreach ($comments as $comment) {
                        if ($comment->parent_id === null) {
                            if (isset($comment->order) === false || $comment->order > $order) {
                                $comment->order = $order;
                            }
                            array_push($commentAndReplies, $comment);
                        } else {
                            foreach ($comments as $parentComment) {
                                if ($parentComment->id === $comment->parent_id) {
                                    $parent = $parentComment;
                                    break;
                                }
                            }
                            foreach ($parent->replies as $replyInParent) {
                                if ($replyInParent->id === $comment->id) {
                                    $reply = $replyInParent;
                                    break;
                                }
                            }
                            if (isset($comment->order) === false) {
                                $comment->order = $order;
                                $order++;
                            }
                            if (isset($parent->order) === false || $parent->order > $comment->order) {
                                $parent->order = $comment->order;
                            }
                            $reply->order = $comment->order;
                            $reply->replies = $comment->replies;
                            $reply[$newType] = $comment[$newType];
                            $basePower = 6;
                            if ($comment->user_id !== null) {
                                if ($comment->user_id === Auth::id()) {
                                    $reply->replyFrom = "me";
                                } else if ($comment->user->role->power >= $basePower) {
                                    $reply->replyFrom = "staff";
                                } else {
                                    $reply->replyFrom = "user";
                                }
                            } else {
                                $reply->replyFrom = "visitor";
                            }
                            $iReplied = false;
                            $staffReplied = false;
                            foreach ($reply->replies as $replyOfReply) {
                                if ($replyOfReply->user_id !== null) {
                                    $power = $replyOfReply->user->role->power;
                                    if ($power >= $basePower) {
                                        $staffReplied = true;
                                    }
                                }
                                if ($replyOfReply->user_id === Auth::id()) {
                                    $iReplied = true;
                                }
                            }
                            if ($staffReplied === false) {
                                if ($reply->replyFrom === "user" && $reply->replyFrom === "visitor") {
                                    $reply->replied = "notReplied";
                                } else {
                                    $reply->replied = "lastWords";
                                }
                            } else if ($staffReplied && $iReplied === false) {
                                $reply->replied = "notByMe";
                            } else if ($staffReplied) {
                                $reply->replied = "replied";
                            }
                        }
                    }
                    $groupAfterOrganized[$content] = $commentAndReplies;
                }
                $langSet[$lang] = $groupAfterOrganized;
            }
            $grouppedComments[$newType] = $langSet;
        }
        return $grouppedComments;
    }

api.php

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

Route::apiResources([
    'languages'     => 'API\LanguagesController',
    'users'         => 'API\UsersController',
    'roles'         => 'API\RolesController',
    'tags'          => 'API\TagsController',
    'categories'    => 'API\CategoryController',
    'pictures'      => 'API\PicturesController',
    'posts'         => 'API\PostsController',
    'comments'      => 'API\CommentsController'
]);

EDIT

I'm using the code down below in RedirectIfAuthenticated.php and when I try with

dd(Auth::user());

it returns null as well. BTW obviosly, redirect to backend doesn't work.

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        if (Auth::user()->role->power > 5) {
            return redirect('backend');
        }
        return redirect(RouteServiceProvider::HOME);
    }
    return $next($request);
}
Community
  • 1
  • 1
Bulent
  • 3,307
  • 1
  • 14
  • 22

2 Answers2

0

The solution to this problem is fairly simple . because you are using api request laravel default auth can not understand the user so here the passport comes :

https://laravel.com/docs/7.x/passport

as written in documenation you should go 3 steps :

composer require laravel/passport
php artisan migrate
php artisan passport:install

after that you can generate token for logged in users and use that token in api authentication to use for your api which is the only and more reliable way that laravel default auth . this link can be helpful to you too :

https://laravel.io/forum/laravel-passport-vue-check-user-authentication

this way if you intent to use you api in mobile or any other application you can simply authenticate your user in that :) hope this helps

EDIT

according To your comment now you must generate token for your vue api to use so this would be like below :

  $token    = $user->createToken(config('app.name'))->accessToken;

        if ($this->isApiType()) {
            $token = $user->createToken(config('app.name'))->accessToken;
        } else {
            Auth::login($user);
            $redirect = $this->getRedirectTo($user);
        }

this must be added in the end of your login method so if the request comes from api it generates a JWT token for you which can be used in vue for login

Community
  • 1
  • 1
Farshad
  • 1,830
  • 6
  • 38
  • 70
  • Passport 8.4 is already installed. And user.php has use Laravel\Passport\HasApiTokens and use HasApiTokens – Bulent Apr 05 '20 at 12:27
  • Thanks, but as far as I understand, you are talking about getting user details in Vuejs. That part is not a problem. I can't get auth user id in controller. – Bulent Apr 05 '20 at 13:11
-1

yes for getting the authencated user detail your API must under the auth:API middleware.

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

 }

As you are using Resource those are not under the Api middleware just put that into that and Auth::user will return the result set.

 Route::group(['middleware' => 'auth:api'], function () {
  Route::apiResources([    
   'comments'      => 'API\CommentsController'
  ]);
 }

will fix the issue.

Noni
  • 369
  • 2
  • 14