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

raffelustig's avatar

Laravel 5.3 system into laravel 7 login problem

I took our old 5.3 version and copied all into a laravel 7 fresh installation. I have got everything to work except I can't login. It seems that it redirect back into the login page after authorization had been done and the oauth_access_tokens och oauth_refresh_tokens have been generated in the database. Register user works fine with confirmaton email, so is reset password if forgotten.

Link to picture of the front page: https://1drv.ms/u/s!AvqgYxcgVT-FgTF-kP2y2X6bIO_-?e=Jae9ig

What could be the problem? It never comes to the AuthenticateController because if I remove that it makes no difference. If I remove AuthenticateController in the working 5.3-system it acts exactly as in this 7-system, oauth_access_tokens och oauth_refresh_tokens generates but nothing more.

Here the parts involved in login. app/Http/Controllers/Api/AuthenticateController.php



    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAuthenticatedUser(){
        $user = \Auth::user();

        $user->makeVisible([
            'email',
            'no_shooting_card_number',
            'shooting_card_number',
            'birthday',
            'phone',
            'mobile',
            'gender',
            'grade_trackshooting',
            'grade_field'
        ]);
        // the token is valid and we have found the user via the sub claim
        return response()->json(compact('user'));
    }

    public function updateAuthenticatedUser(\App\Http\Requests\UserRequest $request){
        try {

            $user = \Auth::user();
            $data = $request->all();
            if($request->has('set_no_shooting_card_number')) $data['no_shooting_card_number'] = date('Y-m-d H:i:s');
            if($request->has('shooting_card_number')) $data['no_shooting_card_number'] = null;
            $user->update($data);
            $user->makeVisible([
                'email',
                'no_shooting_card_number',
                'shooting_card_number',
                'birthday',
                'phone',
                'mobile',
                'gender',
                'grade_trackshooting',
                'grade_field'
            ]);
            return response()->json(compact('user'));

        } catch (JWTException $e) {
            if ($e instanceof TokenExpiredException) {
                return response()->json(['token_expired'], $e->getStatusCode());
            } else if ($e instanceof TokenBlacklistedException) {
                return response()->json(['token_blacklisted'], $e->getStatusCode());
            } else if ($e instanceof TokenInvalidException) {
                return response()->json(['token_invalid'], $e->getStatusCode());
            } else if ($e instanceof PayloadException) {
                return response()->json(['token_expired'], $e->getStatusCode());
            } else if ($e instanceof JWTException) {
                return response()->json(['token_invalid'], $e->getStatusCode());
            }
        }

    }

   

app/Providers/AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

 // Passport::routes();
    Passport::routes(null, ['prefix'=>'api/'.'v'.env('API_VERSION') . '/oauth']);

        //
    }
}

routes/api.php (first part)

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| 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('/auth/register', ['as'=>'auth.register', 'uses'=>'AuthenticateController@register']);

Route::group(['prefix'=>'v'.env('API_VERSION')], function(){
    Route::post('activate', 'AuthenticateController@activate');
    Route::post('register', 'AuthenticateController@register');
    #Route::post('refresh', 'AuthenticateController@refresh');
    Route::post('password/email', 'PasswordController@postEmail');
    Route::post('password/reset', 'PasswordController@postReset');

    Route::group(['prefix'=>'public'], function(){
        Route::resource('competitions', 'PublicCompetitionsController', ['only' => ['index', 'show']]);
    });


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

/** This row is the login reacting on. If I comment it out the login changes to a screen with a mix of headers and footers and if I refresh the screen I am returned to the login page again.**/
        Route::get('authenticate/user', 'AuthenticateController@getAuthenticatedUser');
/**********************/

        Route::put('authenticate/user', 'AuthenticateController@updateAuthenticatedUser');
        Route::put('authenticate/updatePassword', 'AuthenticateController@updatePassword');
        Route::post('authenticate/cancelAccount', 'AuthenticateController@cancelAccount');
        Route::get('users/invite', 'AuthenticateController@getInvite');

resources/views/public/login.blade.php

<div class="row">
	<div class="col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4">
		
		<div class="panel panel-primary">
			<div class="panel-heading">
				{{_('Login')}}
			</div>
			<div class="panel-body">
				<div ng-class="{'hide': loggingIn}">
					<div class="form-group">
						<input type="text" name="email" ng-model="auth.email" id="email" class="form-control" placeholder="{{_('E-postadress')}}" ng-enter="login();" autofocus>
					</div>
					<div class="form-group">
						<input type="password" name="password" ng-model="auth.password" class="form-control" placeholder="{{_('Password')}}" ng-enter="login();">
					</div>

					<a class="btn btn-success btn-block" ng-click="login();" ng-class="{'disabled': loggingIn}">{{_('Logga in')}}</a>
					<div class="row margin-top-20">
						<div class="col-sm-12 text-center">
							<a ui-sref="auth.password">{{_('Forgot your password?')}}</a>
						</div>
					</div>
					<div class="row margin-top-20">
						<div class="col-sm-12 text-center">
							<a ui-sref="auth.register">{{_(No account? Register')}} &raquo;</a>
						</div>
					</div>

				</div>
				<div class="hide text-center text-muted" ng-class="{show: loggingIn}">
					<i class="fa fa-2x fa-spinner fa-spin"></i>
					<p>{{_('Logging in')}}</p>
				</div>
			</div>
		</div>
		
	</div>
</div>

<script>$('#email').focus();</script>

routes/web.php

<?php



#Route::group(['middleware'=>'browserCheck'], function() {
    Route::get('/', function () {
        return view()->make('app');
    });
#});

Route::get('/browser', function(){
    return view()->make('browser');
});

//Route::get('map', 'Api\CompetitionsController@list');
Route::get('map', 'CompetitionsController@list');
Route::get('skapa', 'CreateClubsController@createclub');
Route::post('skapa','CreateClubsController@storeclub');
Route::get('admin', 'CreateAdminsController@createadmin');
Route::post('admin','CreateAdminsController@storeadmin');
Route::get('/files/download', 'FileController@download');

Route::get('/publicviews/{name}', function($name){
    \LaravelGettext::setLocale('sv_SE');
    if(View::exists('public.'.$name)):
        return view()->make('public.'.$name);
    else:
        return response()->json(['message' => _('The page could not be found.')], 404);
    endif;
});

Route::group(['middleware'=>'auth:api', 'checkUserActive'], function(){
    Route::get('/views/{name}', function($name) {
        \LaravelGettext::setLocale('sv_SE');
        if (View::exists($name)):
            return view()->make($name);
        else:
            return response()->json(['message' => _('The page could not be found.')], 404);
        endif;
    });
});

Route::group(['prefix'=>'api', 'namespace' => 'Api'], function(){

});

#Route::group(['middleware'=>'browserCheck'], function() {
    # Catch all segments in public domain
    Route::any('{path1?}/{path2?}/{path3?}/{path4?}/{path5?}/{path6?}/{path7?}/', function()
    {
        return view()->make('app');
    });
#});
0 likes
3 replies
hondnl's avatar

Take a look at the upgrade guides Start at 5.4 and continue with 5.5 , 5.6 etc till you arrive at 7 https://laravel.com/docs/5.4/upgrade

Take a close look at all the changes that have to do with Authenticating and compare your code. You will find something that is currently breaking your code.

raffelustig's avatar
raffelustig
OP
Best Answer
Level 2

This is the error I got everytime I clicked "Login":

[2022-01-10 18:13:36] local.ERROR: count(): Parameter must be an array or an object that implements Countable {"userId":2,"exception":"[object] (ErrorException(code: 0): count(): Parameter must be an array or an object that implements Countable at /Users/ralph/laravelnew/webshooter_web_upgrade/app/Models/User.php:96)
[stacktrace]
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'count(): Parame...', '/Users/ralph/la...', 96, Array)
#1 /Users/ralph/laravelnew/webshooter_web_upgrade/app/Models/User.php(96): count(NULL)

This is the part of User.php:

public function getClubsIdAttribute()
{
if(!$this->relationLoaded('Clubs')):
$this->load('Clubs');
endif;
return (count($this->Clubs->first())) ? $this->Clubs->first()->id : null;
}

Line 96 is the return-line. I got a solution like this from a guy here in Sweden:

if (isset($this->Clubs) && $this->Clubs->first()) return $this->Clubs->first()->id;
else return null;

instead of all the other lines and after that I could login. Very happy about that.

Please or to participate in this conversation.