Access all tutorials in sprocket icon.
August 6, 2015 from author Bill Keck.
Update December 21, 2015 for Laravel 5.2
Just a quick note that Laravel 5.2 now features an artisan command:
php artisan make:auth
This will create the basic views you need for login, registration, and password resets.
You might still want to read through this tutorial, it will give you an idea on how the AuthController works, which is essential later on when you want to modify it. Also, I provide the routes that you will need and we cover the redirectTo property, which will you most likely need as well.
Here is the original tutorial:
User login and registration for laravel 5.1.4 tutorial
In this tutorial, we are going to build the basic user login and registration routes and views. We assume you have a fresh install of Laravel 5.1.4. If you need help setting that up, please reference my Laravel Installation tutorial or visit the laravel.com docs.
We also assume that you have setup your database and run the first migration. If not, please read my tutorial on Database Setup in Laravel 5.1.
Also note, we are going to use Gists, which are online code snippets hosted by Github, for the views, so this will make copy and pasting of the views very easy.
Before we begin, let’s talk about the difference between laravel 5.0 and 5.1 and 5.1.4.
Background
5.0 came with a working user registration and password implementation right out of the box. In some ways, it was very convenient because it gave you the routes, model, controllers, and views that you needed to have instant registration and login. In other ways, it was an awkward implementation. It used, for example, the following route declaration:
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
In this way of doing routing, the verbs on the controller define the type of route, for example:
public function getRegister()
So if you typed in a url such as yourdomain.com/auth/register, it would send you to the getRegister method on the controller. This is perhaps one of the less intuitive and more complicated ways of doing this.
To complicate things even further, the AuthController used a trait to pull in the getRegister method, so that was not even visible directly in the controller.
Taylor Otwell has made an artform out of making things simpler, and this just seemed way overly-complicated.
So when 5.1 released, I expected things to get simpler, and they did to some extent, but they also got a little stranger.
The AuthController was still using traits, but dropped the registrar class, which had formerly created the user, in favor of a more direct approach. That made it a little simpler.
At the same time, none of the routes or the views for login and registration, which came ready-made out of the box in 5.0 were included in 5.1. So unless you were simply upgrading from 5.0 to 5.1, you had to build all that from scratch.
So I wrote this tutorial for 5.1 and eliminated the main trait to make it easier to work with, but then guess what? Within 2 months 5.1.4 was released and Laravel introduced a new feature called login throttling, which made quite a few changes to the out-of-the-box user login and registration solution.
This meant that anyone following this tutorial was following something that was not going to work if they were using a fresh install of Laravel. So having learned from that mistake, I’ve decided to update this tutorial and preserve the original traits that come out of the box. That way if there is another change to a subsequent version, it should not break the code.
I think it’s best to “ride the lightning” of Taylor Otwell’s inventiveness and make the application as easy to maintain as possible. If you are unfamiliar with traits, you will learn a little about them in this tutorial. You can also check out this tutorial on traits.
Ok, here we go.
Part 1. The Routes
Let’s start by adding the following routes in routes file;
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');
// Registration routes...
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');
Route::controllers([
'password' => 'Auth\PasswordController',
]);
You can see we made a get and post route for both register and login and a get route for logout. We are also going to include a route for our PasswordController, which is also included out of the box. I have a separate tutorial for implementation of the forgot password functions, which I will also have to update for this latest version.
Part 2. AuthController
You do not need to create this file, it comes out-of-the-box, you can find it in app/Http/Controllers/Auth:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
While we’re here, we going to add one property that defines our redirectTo path:
private $redirectTo = '/';
So put that directly under the line:
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
Ok, you might be asking, where are all the methods for the login and registration actions? As in the previous versions, these are in the traits. We will return to those in a moment, but let’s first walk through what we have in the AuthController class.
I’ll skip the use statements and class declaration, those are pretty self-explanatory.
So moving along, we have the constructor:
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
What it’s doing here is limiting access to the methods to guests, except for the getLogout method. Obviously if you already authenticated, you do not need to login or register. However you would need to be able to logout, which is why we have this exception.
This is a beautiful example of the Laravel middleware at work. I will go deeper into that in a separate tutorial.
Next we have a validator method:
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',
]);
}
This is setting the rules for the form inputs. Obviously, if you want more fields on your form, you would add more rules here, and also to your DB and User model.
Next we have the create method:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
This method creates the new user upon registration.
Ok, so you can see there isn’t much on the surface of the AuthController. That’s because most of the methods are in the traits that we are using. We will cover those next.
Part 3. The Traits
Ok, so for anyone who doesn’t know, a trait is a class that can be used by multiple classes in a way that is like inheritance. You simply call the trait through the use statement and then all of the methods of the trait are available to the class that is using it. It’s a really cool and efficient way to handle code that will be reused by multiple classes.
I’m covering this to give you a quick idea of how it all works. We are not changing anything here however, so you can skip this part if you are in a hurry and want to go directly into the views.
Anyway, you can see AuthController uses 2 traits:
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
Let’s look at:
namespace Illuminate\Foundation\Auth;
trait AuthenticatesAndRegistersUsers
{
use AuthenticatesUsers, RegistersUsers {
AuthenticatesUsers::redirectPath insteadof RegistersUsers;
}
}
You can see this trait just pulls in two other traits, and also declares which method to use in case of conflict, since both traits, AuthenticatesUsers and RegistersUsers have a redirectPath method.
Ok, so we go another layer into AuthenticatesUsers:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Cache;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function getLogin()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('auth.login');
}
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @param bool $throttles
* @return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::user());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the needed authorization credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password');
}
/**
* Get the failed login message.
*
* @return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Log the user out of the application.
*
* @return \Illuminate\Http\Response
*/
public function getLogout()
{
Auth::logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
/**
* Get the path to the login route.
*
* @return string
*/
public function loginPath()
{
return property_exists($this, 'loginPath') ? $this->loginPath : '/auth/login';
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function loginUsername()
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* @return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(get_class($this))
);
}
}
And you can see this trait has all of our login methods. I’m not going to cover these in detail because we are not changing anything and we are simply using what is provided.
Let’s take a quick look at the RegistersUsers trait:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait RegistersUsers
{
use RedirectsUsers;
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function getRegister()
{
return view('auth.register');
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}
}
And so this gives us the methods we need to register a user.
Obviously a benefit to separating out authenticating and registering into separate traits is a less bulky controller and a more focused codebase.
Our AuthController is also using the ThrottlesLogins trait:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Cache;
trait ThrottlesLogins
{
/**
* Determine if the user has too many failed login attempts.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function hasTooManyLoginAttempts(Request $request)
{
$attempts = $this->getLoginAttempts($request);
$lockedOut = Cache::has($this->getLoginLockExpirationKey($request));
if ($attempts > $this->maxLoginAttempts() || $lockedOut) {
if (! $lockedOut) {
Cache::put(
$this->getLoginLockExpirationKey($request), time() + $this->lockoutTime(), 1
);
}
return true;
}
return false;
}
/**
* Get the login attempts for the user.
*
* @param \Illuminate\Http\Request $request
* @return int
*/
protected function getLoginAttempts(Request $request)
{
return Cache::get($this->getLoginAttemptsKey($request)) ?: 0;
}
/**
* Increment the login attempts for the user.
*
* @param \Illuminate\Http\Request $request
* @return int
*/
protected function incrementLoginAttempts(Request $request)
{
Cache::add($key = $this->getLoginAttemptsKey($request), 1, 1);
return (int) Cache::increment($key);
}
/**
* Redirect the user after determining they are locked out.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendLockoutResponse(Request $request)
{
$seconds = (int) Cache::get($this->getLoginLockExpirationKey($request)) - time();
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getLockoutErrorMessage($seconds),
]);
}
/**
* Get the login lockout error message.
*
* @param int $seconds
* @return string
*/
protected function getLockoutErrorMessage($seconds)
{
return Lang::has('auth.throttle')
? Lang::get('auth.throttle', ['seconds' => $seconds])
: 'Too many login attempts. Please try again in '.$seconds.' seconds.';
}
/**
* Clear the login locks for the given user credentials.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function clearLoginAttempts(Request $request)
{
Cache::forget($this->getLoginAttemptsKey($request));
Cache::forget($this->getLoginLockExpirationKey($request));
}
/**
* Get the login attempts cache key.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function getLoginAttemptsKey(Request $request)
{
$username = $request->input($this->loginUsername());
return 'login:attempts:'.md5($username.$request->ip());
}
/**
* Get the login lock cache key.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function getLoginLockExpirationKey(Request $request)
{
$username = $request->input($this->loginUsername());
return 'login:expiration:'.md5($username.$request->ip());
}
/**
* Get the maximum number of login attempts for delaying further attempts.
*
* @return int
*/
protected function maxLoginAttempts()
{
return property_exists($this, 'maxLoginAttempts') ? $this->maxLoginAttempts : 5;
}
/**
* The number of seconds to delay further login attempts.
*
* @return int
*/
protected function lockoutTime()
{
return property_exists($this, 'lockoutTime') ? $this->lockoutTime : 60;
}
}
I’m not going to cover the entire trait, but I will say this is a cool feature that they have added to the login methods. It helps cut down on attacks from bots that will attempt to login over and over until it finds a successful user/pass combo.
It’s also easy to control the settings. You can see for example, that if you wanted to set the maxLoginAttempts to a number other than 5, you can include on your AuthController, a property:
private $maxLoginAttempts = 10;
That would get returned in the maxLoginAttempts method in the ThrottesLogins trait that the AuthController is using.
Part 4. Views
Ok, so now we need the views to support the registration and login forms.
A quick note about the app master page. A master page is a view file that would typically get included on every page. But instead of including it on other view pages, it works in reverse. The view pages are injected into the master page at specific locations.
I will write a separate tutorial for this, explaining it in more detail. For now, just know that we will be including the following into our views:
@extends('layouts.master')
@section('content')
// our view content goes here
@endsection
If you don’t have a master.blade.php file residing in a layouts folder inside of views, then don’t use this syntax at all and just use the what goes in between the @section tags.
Also note, that while we will be including a forgot password link on our login form, we have not yet built that functionality. I will build that will be a separate tutorial.
Ok, let’s create a couple of folders within our view folder. Our view folder is located at app/resources/views.
Make an auth folder and an email folder, each folder should reside directly under the views folder, so they have the following paths:
app/resources/views/auth
app/resources/views/email
We are creating the email folder because we will need it later in a subsequent tutorial, for now you can put an empty stub in there named password.blade.php.
Within the auth folder, make a register.blade.php file. For those unfamiliar, the convention we follow to use the blade template engine is viewname.blade.php. That tells the compiler it is a blade file and compiles it for you.
I’m going to provide a gist here, which has the code and will open in a new tab. You can copy the code from here:
A lot of this is just straight Twitter Boostrap, so if you are unfamiliar with that, I suggest you take some time to visit getbootstrap. Our tutorial is not going to teach you html or css. We will be focusing on the blade specific elements and the content specific to our application, in this case the registration form.
Ok, so the first item of interest to us in the Gist is the if statement that holds the errors. Here we are using Blade’s @if syntax to make the interspersing of html and php a pleasure to work with.
As you might already be aware, the $errors object is always available to the views. That means we can use a simple foreach loop to parse and print. So if the count of errors is greater than 0, then we serve a notice:
Whoops! There were some problems with your input.
We follow that with the @foreach, using $error as the local variable, then we use the {{ }} syntax, which is short for , to print each error as a list item.
Normally what you will do is extract this block out to view partial and just include it with the line:
@inlcude(‘errors.errors’)
This would assume you have an errors folder inside the views folder with view file named errors.blade.php.
For this tutorial, we are leaving it in the main view, but you’ll certainly want to extract as I’ve described above because it doesn’t make sense to repeat this code.
Ok, let’s move on to the form itself. We open it with:
<form class="form-horizontal" role="form" method="POST" action="/auth/register">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Note that there are two ways to begin the form. The manual way is how we are doing it here. But Laravel also has a helper class that allows you to do it as follows:
{!! Form::open(array('url' => '/auth/register, 'class' => 'form-horizontal')) !!}
You can see this is a lot simpler and it includes the CSRF token for you automatically.
If you want to do it that way, you need to pull in the illuminate Html helper class, which you can find at:
https://github.com/illuminate/html
Just follow the instructions there.
Anyway, for now we are going to stick with:
<form class="form-horizontal" role="form" method="POST" action="/auth/register">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Next we have our form-group for the name input field. Refer to the Gist for the code.
You can see we also have a value of {{ old(‘name’) }} so that the form remembers the input. Otherwise, this is just standard bootstrap form syntax.
Next we have the two password fields, so the user is typing in what they intend and not making a typo. But how does it know to compare the two password fields and validate them?
IF you remember, we had in our validator method in our AuthController:
'password' => 'required|confirmed|min:6',
You can see the middle rule is confirmed, so it’s looking for password_confirmation from the form post and performs its validation. This is unbelievably easy to work with, since you don’t have to set up a class property or do anything else for it.
If you wanted to confirm any other input, you would simply use the _confirmation syntax on the 2nd field and then make sure you had confirmed as one of the validation rules.
Finally, we have the submit button and closing form tag and that should get you a working registration form.
Note: If for some reason you passing validation but not saving to the DB, check the $fillable property on your User class, which is located in the app directory. You have to explicitly name the properties which are mass assignable.
protected $fillable => ['name', 'email', 'password'];
Ok, let’s move on to the login view. Let’s create a login.blade.php file within the app/resources/views/auth folder with the following contents:
Ok, so we have the errors section again, which just points to how much better it would be in a partial, as I described in the registration view section. Then we come to the login form itself, which starts as we would expect:
<form class="form-horizontal" role="form" method="POST" action="/auth/login">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Next we get the email and password fields, nothing new here, so I won’t list it again.
Then we get a checkbox for the remember me, which if checked will set a cookie. The value of remember gets passed in the Auth::attempt method in the AuthenticatesUsers trait:
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
Then we get the submit button and forgot password link and that should be it, you should now have a working user registration and login. You should be able to test the following routes:
yourapp.com/auth/login
yourapp.com/auth/register
yourapp.com/auth/logout
I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks.
I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.
Exactly what it needed.. Thank you.. It’s pitty to see such jumpings on a such successfull framework.
LikeLike
Lovely Explanation
LikeLike
Hi Bill,
I followed your instructions and they are really good! But I have a question for you. I followed your steps and also created and migrated my database with user login/registered data. But when I try to register a person, I get an error as you can see below:
FatalErrorException in RegistersUsers.php line 32:
Call to a member function fails() on null
Do you know how I can solve this?
LikeLike
Sounds like it’s not getting the value to validate, so if it’s getting null, then it can’t validate. Check your form labels for a typo.
LikeLike
I checked my form labels, but can’t find something weird. I also tried to copy it from you gist example which link was provided in the text. But even then it still gives the error… You can see my file (and other files in my laravelproject) on: https://github.com/RobbieBakker/LaravelProject56/blob/master/http/laravel/resources/views/auth/register.blade.php
LikeLike
ok, so that looks like it should work. When you are in a situation like this, you need to use dd(), the die dump function to test your way through the process to see where it’s failing.
LikeLike
Okay thanks, I’ll try that! Until now it seems that logging in works fine, but registering gives the error.
LikeLike
Because I’m quite new to PHP and Laravel, I’m not really familiar to the dd() function. How and where do you recommend me to use it?
LikeLike
dd($yourVariableOrObject); You can use it anywhere and it will output the contents of the variable or object. It’s their die dump function and it’s extremely useful…
LikeLike
I avoided the problem by just commenting the function which called the exception. Not sure if it’s the way how it should be solved, but everything seems to work fine now. 🙂 Thanks for your support!
LikeLike
I get NotFoundHttpException in RouteCollection.php line 161: for all the three routes except the ‘welcome’ route after following this tutorial
LikeLike
Did you add the necessary routes in the first place?
LikeLike
I have the same error.
LikeLike
Hi Bill
I am using the same tuts with Laravel 5.2.24 but receiving this errors when i try to logged in or to access home page after registration
FatalThrowableError in EloquentUserProvider.php line 130: Fatal error: Class ‘\User’ not found
Please any helps ?
LikeLike
you are probably missing a use statement.
LikeLike
thanks it’s a work
LikeLike
How can I create signUp api for mobile app using Laravel. I have been scratching my head over this for a while now. I am a newbie to php and laravel.
LikeLike
Laravel 5.2 supports token-based auth, there is a Laracasts episode on that available at http://www.laracasts.com. If you have a programming background, you can pick up PHP and Laravel easily. Laravel has an especially intuitive syntax that most programmers find very appealing.
LikeLike
Thanks Bill for the insight. Does this mean that we do not need php-jwt package to support token based authentication system. I am iOS developer and want to write mobile api using Laravel. I could not find a way to write the signUp api although I did login using php-jwt and I have also created other apis but I am not getting signUp to work.
LikeLike
I’m not sure about that, I have not use jwt for authentication myself personally yet. Let me know how this goes for you, perhaps you can come back and do a guest tutorial or article or something…
LikeLike
I actually am struggling with this same issue. Auth with a valid token isn’t really the challenge. The problem is that you can post directly to the /register route to create a new user, but if there’s an error, it doesn’t return the error to the client application. All attempts just redirect to / with no success/failure feedback. I’m trying not to have to duplicate the whole auth mechanism just to get this working, but I can’t seem to find a straightforward way to handle it. See here for more detail: http://stackoverflow.com/q/38078512/5425432
LikeLike
Sorry, if I understand you correctly, what you are trying to do is outside the scope of the tutorial. I try to follow the baked in way of doing it because it saves a lot of headaches.
LikeLike
I’m definitely not trying to do anything far out here. But, like the person mention in the original comment, I need my mobile app to be able to create and modify users through REST calls (without directing people to a web page). I can tell there’s an easy way to accomplish this without reinventing everything, but I’ve struggled to actually find that solution. I think the simplest answer might be to just build an alternate view controller for the registration page and, instead of returning a blade template, just return response()->json($errors). I’ll play with it tonight and see if I can make that work.
LikeLike
hello..
after install laravel when i write php artisan make:auth in cmd, it gives error like command make:auth not defined..
please reply..
LikeLike
make sure you are running laravel 5.2. Then you can run php artisan list to see if the make:auth command is in there. It should be. As of laravel 5.2.31, the make:auth command is still there.
LikeLike
ohk…but can i install laravel 5.2??how??i m new to laravel..
LikeLike
I’m using Laravel 5.1 and I’ve followed this tutorial as best I could. When I submit my logon credentials, I get this error:
“`BadMethodCallException in ServiceProvider.php line 234: Call to undefined method [setPresenceVerifier]“`
I’ve found this post https://laracasts.com/discuss/channels/laravel/validation-setpresenceverifier-error-in-custom-validation-class wherein the auhor says they added the presence verifier to their custom validation class. But, since I’m not using a custom validation class, I am not sure where to add that.
Has anybody else encountered this problem and resolved it?
LikeLike
In Laravel 5.2 and above, php artisan make:auth will get you all the forms and a working registration and login on a fresh install, as long as your DB is configured. I have not encountered the problem you are describing. The subsequent versions of Laravel, 5.2 and 5.3, are easier to work with and I would encourage you to work with the a newer version if you can. The framework just gets better and better.
LikeLike
Thanks for you help, Bill, and your great tutorial. My problem was actually related to some custom validation code that I had stupidly chosen not to develop in a branch.
I had chosen laravel 5.1 because it was labeled LTS. I had hoped that it would provide some stability, and not have to stay on the bleeding edge : /
LikeLike
Your 5.* book — is it easy to distinguish what version of Laravel any particular piece of information belongs to?
LikeLike
The last version of that book is for 5.2. I will not be updating it because 5.3 represents a significant leap in accessibility for beginners in subjects such as Elixir and Vue.js and I’m writing a lot of new material for that. The architecture is just beautiful. I’m working on a new book for 5.3, which will be released around the same time as the official launch of 5.3, which is very soon. Laravel evolves very quickly, but rather than fight or fear that, I’ve embraced it, and the framework just keeps getting more amazing.
LikeLike
I’m not really afraid of that — I decided to do a project in Laravel to learn something new– I just wish 5.1 wasn’t called Long Term Support if it’s not going to be recommended during its lifetime. It’s just only over a year old.
If in a year’s time the solutions to the problems I encounter with 5.2 are to upgrade to 5.3 or later, I’m not going to be a happy camper. How much rewriting will I have to do when I upgrade?
LikeLike
I’m not an official member of the Laravel team, so my recommendations do not have anything to do with them or their long term support. If you are working on a giant project, then it’s not practical to constantly update. For smaller projects, you can update the project quickly. The thing is, you get more capabilities out of each subsequent version and I think that’t totally worth it. I wasn’t using Elixir until recently, and Laravel 5.3 just made it easy to set that up with Vue.js, it comes configured out of the box. So I was able to adapt my Vue.js datagrid to a very robust module/component architecture that is easy to work with. Prior to 5.3, I chose not to use Elixir because I wasn’t doing anything sophisticated enough to justify it. Now I wouldn’t dream of not using it. Laravel is also evolving to handle stateless authentication. I have not used that myself, but it is very robust. It’s an enterprise framework, which many companies are using, so it’s worth staying current on, in my opinion. I’m going to do a longer blog post about it after I have finished my book.
LikeLike
Hi,Bill
How can I store users details in different Table instead of “Users”(Default) table…
Please Help me !!!
LikeLike
That’s beyond the scope of the tutorial, and unless you like coding all the authentication and password recovery stuff from scratch, it’s a really bad idea…
LikeLike
hello, first of all Thank you for your tips . But I wonder path that have ThrottlesLogins,AuthenticatesUsers traits. Can I paste on AuthController.php file?
LikeLike
Hi, I’m not sure I understand your question correctly. Also, if you are looking for basic auth out of the box, install Laravel 5.3, and run php artisan make:auth It will create the views for you.
LikeLike
i hove one issue i want o show first registration page then login then show the welcome page but when i run the program the show the first welcome page
LikeLike
I don’t understand you problem. You want them not to be logged in after registering? If so, on 5.3, you will need to modify the RegistersUsers trait.
LikeLike
I have generated login using php artisan make:auth command in laravel 5.2. I do not need it any more. I want to remove this login/logout/signup and other files generated by this command. HOW ?
LikeLike
remove the files manually.
LikeLike
Hello, I’ve followed every bits and pieces of this tutorial but when I login I don’t get an error but it’s keep me redirecting to the login page. Any clue on that?
LikeLike
If you are using Laravel 5.3, please use the php artisan make:auth command with a fresh install of Laravel. It will create all the views and home controller for you. The tutorial for 5.1 will not be appropriate for 5.3. You can check your version by running php artisan -V from the command line. Hope that helps.
LikeLike
Hello, what would do you mean if I added more fields I would need to change the “user model”?
I’m trying to create a site after installation of laveral and would need post processing of user inputted data, i.e an alogrithm working with additional fields where users input values etc. Is this possible?
Thanks,
LikeLike
In Laravel 5.5, creating login and registration with authentication (https://www.cloudways.com/blog/laravel-login-authentication/ ) is really easy. All you have to do is just use the php artisan make:auth command after migration. If you want to create a custom authentication, then this method won’t work.
LikeLike
New to your blog. Stumbled upon it browsing the web. Keep up the great work. I am hoping you update it regularly.
LikeLike
Thanks for sharing this great information here,it was really helpful to me.
LikeLike
its very helpful tutorial thank you for sharing. keep doing good work.
LikeLike