Starting Authentication On Laravel

In Laravel you can easily create an authentication, because laravel has provide us a default function from Laravel. You can use it right after you generated the function to your project. To generate it you only need to run this command on you command prompt.

php artisan make:auth

After you run that command there must be a new file in controller, you can customize these file to your on condition.

If you want to change path where user go after user authentication success, by default they will redirected to ‘/home’ to change that you can customize redirect path by defining ‘redirectTo’ in LoginController.

protected $redirectTo = ‘/’;

Or you can defining redirectTo as a method by doing that you can add your own logic before user get redirected.

protected function redirectTo(){return ‘/path’;}

After you customize those file you can’t use it right now, you’ll need to do migration to create a database for authentication, to do that you only need to run this command on your command prompt.

php artisan migrate

After migration complete you can use it now. By default Laravel use ‘email’ field for authentication, if you want to change it, you can do it by defining username method on controller.

public function username()
{
return 'username';
}

Retrieving Authenticated User Data

You can access authenticated user data via auth facades, for the example you can get username of authenticated user.

use Illuminate\Support\Facades\Auth;$user = Auth::user();

You can get their id too.

use Illuminate\Support\Facades\Auth;$id = Auth::id();

Protecting Route

You can protect your by attaching middleware to route definition.

Route::get(‘/home’,’Controller@go’)->middleware(‘auth’);

Or you can use it on controller by define it in construct method.

public function __construct()
{
$this->middleware('auth');
}
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade