3

I develop site with laravel 5.2 and use

https://github.com/mcamara/laravel-localization and

http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/

i have followed everything in that link

my routes.php

Route::group([
'prefix' => LaravelLocalization::setLocale(), 
'middleware' => ['web', 'localize', 'localeSessionRedirect', 'localizationRedirect']
], function () {

    //Route::auth();
    Route::get('login', 'UserAuthController@showLoginForm');
    Route::post('login', 'UserAuthController@login');
    Route::get('logout', 'UserAuthController@logout');

    //user
    Route::get('user/dashboard', ['as'=> 'user/dashboard', 'uses' => 'UsersController@index']); 
});

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

    //Admin Login Routes...
    Route::get('/admin/login','Admin\Auth\AuthController@showLoginForm');
    Route::post('/admin/login','Admin\Auth\AuthController@login');
    Route::get('/admin/logout','Admin\Auth\AuthController@logout');

    Route::get('admin/dashboard', 'Admin\DashboardController@index');

    Route::resource('admin/administrator', 'Admin\AdminController',['except' => 'show']);

UserAuthController.php

namespace App\Http\Controllers;

use Validator;
use Auth;
use Session;

use Illuminate\Http\Request;

use App\Http\Requests;

class UserAuthController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required',
            ]);
        if ($validator->fails()){
          // If validation falis redirect back to login.
          return redirect('login')
                        ->withErrors($validator)
                        ->withInput();
        }else {
          $userdata = [
                'email' => $request->email,
                'password' => $request->password
              ];
          // doing login.
          if (Auth::guard('user')->validate($userdata)) {
            if (Auth::guard('user')->attempt($userdata)) {
              return redirect('/user/dashboard');
            }
          } 
          else {
            // if any error send back with message.
            Session::flash('error', 'Something went wrong'); 
            return redirect('login');
          }
        }

    }

    public function logout()
    {
        Auth::guard('user')->logout();

        return redirect('login');
    }
}

UsersController.php

namespace App\Http\Controllers;

use Auth;

//use Session;

use App\User_Profile;

use Illuminate\Http\Request;

use App\Http\Requests;

class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        session()->put('uid',Auth::guard('user')->user()->id);
        session()->put('username', Auth::guard('user')->user()->username);
        session()->put('email', Auth::guard('user')->user()->email);

        $uid = session()->get('uid');
        $username = session()->get('username');

        $profile = User_Profile::where('user_id', '=', $uid)->first();

        return view('users.index', compact('username', 'profile'));
    }
}

Admin\Auth\AuthController.php

namespace App\Http\Controllers\Admin\Auth;

use App\Admin;
use Validator;
use App\Http\Controllers\Admin\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{


    protected $redirectTo = 'admin/dashboard';
    protected $guard = 'admin';
    protected $redirectAfterLogout = 'admin/login';


    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }



    public function showLoginForm()
    {
        if (view()->exists('auth.authenticate')) {
            return view('auth.authenticate');
        }

        return view('admin.auth.login');
    }
    public function showRegistrationForm()
    {
        return view('admin.auth.register');
    }  
}

my kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        // \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        // \App\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],
        // 'auth' => [
        //     \App\Http\Middleware\Authenticate::class,
        //     \App\Http\Middleware\EncryptCookies::class,
        //     \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        //     \Illuminate\Session\Middleware\StartSession::class,
        //     \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        //     \App\Http\Middleware\VerifyCsrfToken::class,
        // ],
        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
        'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
        'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
        'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
        'user' => \App\Http\Middleware\RedirectIfNotUser::class,
    ];
}

config/auth.php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'user',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'user' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ]

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],

        'admin' => [
            'provider' => 'admin',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

I have success in admin logged in and do anything to manage backend

but not in user, everytime logged in when i refresh keep redirect back to login page. it seems $this->middleware('auth') not working.

Can you help me, where did i miss ?

Thank you

1
  • Could you find solution ? Commented Sep 10, 2016 at 5:36

2 Answers 2

-1

Be sure to have the forms in your views (the login-form, registration-form, ...) post to the localized url's.

So in your blade-views use:

<form method="POST" action="{{ url(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), '/password/email')) }}">
    ...
</form>
Sign up to request clarification or add additional context in comments.

Comments

-1

The above scripts are alright.

I made a mistake in the view, I placed

<a href="{{Auth::guard('guard_name')->user()->logout())}}">Signout</a>

logout function in the navigation view.

I have changed the link with usual logout link.

<a href="{{url('logout')}}">Signout</a>

Now its working.

thanks

3 Comments

Why the -1 on my suggestion below?? I suggested to check your view and i was right the error was in there. You didn't post your view in your question, so nobody could've known where the error was. And btw, my suggestion solved a lot of problems for me with multiple authentication and localization..
PS. When logging out like in your example with a non-localized url it's no problem, but still i suggest to prefix all the links with the selected localizationcode. Especially when posting data, for example logindata.
Hi, Sorry, about the post. I found the solution two days after i post the question, and right now i have a time to update my post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.