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

nmeri17's avatar

How to auth with Laravel 5.4

I keep getting all sorts of funny errors just by trying to see an application can actually work in Laravel and that it's not a myth. First, I had to wrestle with all the suggestion on this issue. Painfully, the answer that helped me was the penultimate on such a long long thread of framework contributors living in denial. I've encountered dozens more, scoured tutorial sites, read this official doc on Laravel auth and stackoverflow questions with outdated answers to the cryptic errors I've been riddled with.

Some of the errors would have been avoidable if my auth table name was simply "users" and even now I've changed to "users", I'm still stuck.

I eventually logged in at some point by removing this line

$this->middleware('auth');

from the HomeController constructor then manually setting up my own auth like I would have done in 30mins if I was developing from scratch. But it felt contrived. The tutorials say everything should work out of the box without touching any native PHP functions so I uncommented the line and continued writhing.

The present situation is that the login form just lies there even though I've manually seeded my database. From the web.php file (which I understand is neo routes.php), I have

Route::post('/login', 'HomeController@loginPost');

Then in its controller, the latest snippet I've tried is this

public function loginPost() {
        var_dump(Input::all());
        if (Auth::attempt(Input::all())) {
            var_dump('expression');
        User::create([
        'username' => strtolower(Input::get('username')),
        'password' => Hash::make(Input::get('password')),
        ]);

$user = User::where('username', '=', strtolower(Input::get('username')));

Auth::login($user);
        }
        else var_dump('expression2');
    }

It's probably supposed to be email there instead of username but I did a replace all in the view, swapping email for username since the application's authentication ID should be their usernames and not their emails. When I hit enter now, the page just reloads with empty input fields. It's even tired of throwing errors at me. Is there a way out or is Laravel just not for me?

0 likes
37 replies
bipin's avatar

this error arise because of predefine code in vendor folder which version you are using of laravel do not modify anything in controller you can override these predefine code from your controller

nmeri17's avatar

@bipin you said I shouldn't modify anything in the controller, then you say in the next line I should override my controller. Do I need extra classes besides the HomeController default class?

abusalameh's avatar

as simple as

php artisan make:auth

will auto generate all routes and views for authentication :)

nmeri17's avatar

@abusalameh I'd already done that before so redoing kept asking if I wanno overwrite the views. This time though when it was done and I tried logging in, the error message says

Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from users where id = nmeri17 limit 1

How do I make it search with username instead of ID. The username that corresponds to the seeded email is nmeri17.

jbowman99's avatar

@nmeri17

trying to find id=nmeri17 will fail if your username is nmeri17. The id will be 1,2....

did you modify your users table?

if you did make:auth you should be able to register and login a user without modfiying anything, all the routes and views are already there. you do have to php artisan migrate

you have to overwrite the default authentication methods if you want to switch the credentials to username and not use the email

abusalameh's avatar

**Username Customization

By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController

public function username()
{
    return 'username';
}
Snapey's avatar

It just works out of the box.

You don't do your "laravel is crap, I could have done this in 30 minutes" case any favours when you do this;

if (Auth::attempt(Input::all())) {
        User::create([
        'username' => strtolower(Input::get('username')),
        'password' => Hash::make(Input::get('password')),
        ]);

so just so that we understand each other, you check the users login credentials and then create a user ??

1 like
nmeri17's avatar

Sorry for the delay in responding guys; I momentarily lost access to my machine.

@jbowman99 I've already modified table users to contain column remember token. I can't find where I'm required to also have column ID. The actual problem is that I'm not in charge of that query. This query

"Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from users where id = nmeri17 limit 1".

Where do I get to change it so I can conveniently replace ID there with username instead?

@abusalameh I also tried your suggestion and it reverted to the dormancy I had when I first opened the thread. When the form is submitted, the page just reloads with the email address. No errors or anything.

@Snapey

so just so that we understand each other, you check the users login credentials and then create a user ??

huh? :confused: I said I already created a model schema and data. I just want to log in and see that laravel is a real thing. I'm not even in the development phase yet and this has been going on for several weeks. I can show you earlier threads I created if you want. The credentials I'm entering in the login form are the exact ones I seeded the table users with except the password which I first converted to its hash equivalent.

One thing I observed is that there is no method in the controller nor routes for handling post requests to the login or register. Which is probably why the page just reloads when the form is submitted. That's why I began messing around with the loginPost method and all those static methods in there. You insist everything works out of the box it isn't here. I've reinstalled laravel even (with all the losses I incurred in so doing)

Snapey's avatar

You understand what this does then?

User::create([
        'username' => strtolower(Input::get('username')),
        'password' => Hash::make(Input::get('password')),
        ]);

remember, this is a trick question. This is your code... what you wrote...

Just start again in a clean directory. Run the php artisan make:auth then play around with USING it. Understand HOW it registers new users. What happens when you login or request a password reset etc.

Once you have done that, and you are starting from a base of it working, you can think about refactoring to work the way you want it to work if you have some unusual use case.

Alternatively you can think, you know what, this does most of what I need, I will leave it alone for now and concentrate on the rest of my application then come back to this later when I understand the framework better

Authentication is a vital part of the safety of your application - dick around with it and get it wrong and you risk yours and your user's data.

2 likes
J_shelfwood's avatar

I agree with @Snapey . Try a new installation and just take it slow like it says in the documentation.

Also, most of the things you are trying to do are covered in Jeffrey's laravel tutorials, according to your profile you haven't watched a single tutorial... A good way to start would be the Laravel From Scratch series.

nmeri17's avatar

@Hawkleaf videos don't really work well on me. I pick up when it's something more interactive or hands on. Books are better. Concise tutorials are best. But the major point is, bandwidth is highly exorbitant in my country so I can't presently afford to watch those videos.

@Snapey methinks what it does is pretty clear: They're trying to create a User instance for this session but the User constructor only yields an instance when contents of the form matches what's in the database. How am I supposed to study what happens in the files when the controller methods are probably altered in microseconds?

All of this sounds like I'm a convoluted pedantic biased against Laravel. That's why it seems like a myth to me because none of you experienced all the horrors I have described.

On closer inspection, I observed this line

 'username' => strtolower(Input::get('username' ))

when the view clearly has an email input instead. In the oversight's defence, I carelessly copied the snippet just to see Laravel work at least. So I changed all occurrences of username in that method to email and the new error is TokenMismatchException.

I also think it's funny that after running make:auth and the subsequent disappearance of method loginPost, attempts to login threw no errors informing me that method was undefined. They probably have __get somewhere in these 1000 files sweeping that error under the rug and moving on while I bang my head in search of a solution.

TokenMismatchException means a new session has been created but the ID doesn't rhyme with what's in my page header (or something like that). I have an idea cuz I bore that cross at some point before coming here. The circular hole of torment smh.

Snapey's avatar

They're trying to create a User instance for this session

NO. This is creating a new user record in the database. User is the model, Create is the method. This code is what you would find in registration of a new user.

TokenMismatchException means a new session has been created but the ID doesn't rhyme with what's in my page header (or something like that).

Token mismatch means you have POSTed a form to the server without including a CSRF field that proves that the form originated from your application.

Its these basics that need covering with the laravel from scratch series or many of the written tutorials that are out there.

That's why it seems like a myth to me because none of you experienced all the horrors I have described.

Why do you think that is? I'll tell you... its because we can follow guidance.

nmeri17's avatar

its because we can follow guidance.

Lol. OK.

many of the written tutorials that are out there.

You're going to recommend one I can use to sign in right? I mean, that's the whole point of the thread no?

nmeri17's avatar

C:\wamp64.2\www\laravel>php artisan migrate Migration table created successfully.

[Illuminate\Database\QueryException] SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre ady exists (SQL: create table users (id int unsigned not null auto_incr ement primary key, name varchar(255) not null, email varchar(255) not n ull, password varchar(255) not null, remember_token varchar(100) null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

[PDOException] SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre ady exists

@Snapey What's the next step sir?

The preexisting table there is belongs to the application I'm trying to rebuild with laravel so a fresh table is unacceptable--the columns contain data I imported from the old table.

Snapey's avatar

for familiarisation, start with a fresh database or rename your existing table. you can come back to your old data later

nmeri17's avatar

Done. That worked to a certain degree: I wasn't sent an email when I tried signing up. Then why I tried logging out, I got this

ErrorException in GenericUser.php line 46: Undefined index: username

Googled a bit for a solution to that without success.

Snapey's avatar

Sending and email (for verification) is not done out of the box.

As we don't know what GenericUser.php is we can't really help there.

Snapey's avatar

What version are you using? Have you started with an earlier version and migrated?

Latest version does not use 'username' (not sure it has ever).

nmeri17's avatar

No sir. Thread title says the OP is using version 5.4. That would mean he's on the most recent version.

nmeri17's avatar

It's not different. I said line 46 not 34.

You reference a non-existent column name - hence the error.

How is this possible when I'm not calling or invoking anything? What's the column name I'm referencing?

Snapey's avatar

examine line 34 in your code and in the laravel source via the link i gave

nmeri17's avatar

I've seen the difference. How am I supposed to know about how both code bases are different when I've been following your orders of letting default auth take control? Anyway I've manually changed that line to "id" and now the error I'm getting is TokenMismatchException in VerifyCsrfToken.php line 68:. I copied all the code from that github file you sent into mine just to remove any other differences but it still throws the same error.

J_shelfwood's avatar

@nmeri17 Are you using the standard scaffolded login form for your login? If not you probably forgot putting

{{ csrf_field() }} 

inside your form field. It is required for a form to be accepted and processed by laravel.

I do recommend you don't alter any source code, especially when you don't fully understand the framework yet. It only makes it harder to search for solutions as our problem becomes way too specific.

nmeri17's avatar

I removed it initially when I saw that error the 1st time. After running make:auth, new views were generated with their default values (which included that csrf token BTW). So it's there. But back when I removed it and kept getting the same errors, what I did was copy the token lying in the form and pasting it in the Head token.

That's the problem with using motley code written by strangers. When something goes wrong, you neither know what to touch nor where to go except rely on "community". Community is invisible like renegade militants. Nobody is really responsible for your problems and you're at their mercy like I've been these past weeks. This whole process felt like learning programming afresh--it took me back to those horrendously dreadful days when I'd be stuck on one problem for weeks and none of those I looked up to would help. Several years later, I haven't encountered a problem on the web that defied a day of me scraping at. But here I am, getting screwed in every single hole by Laravel just because.

Snapey's avatar

You SHOULD NEVER EDIT FILES IN THE VENDOR FOLDER

No one forces you to use the framework. I do it because 10's of thousands of eyes have looked at the code and perfected it.

But you know better than everyone.

Have you considered Ruby on Rails?

nmeri17's avatar

Nope I haven't. I heard it's the easiest/most modern language out there so it'll take some time before I look that way.

I never said or inferred I'm better than anybody. And you're not correct about nobody forcing me to use the framework. It is on every single PHP job listing requirement. I have no choice except to suffer like this.

I haven't even set up shop. I barely just got the ball rolling by forfeiting my table. But I cannot log out. I can imagine how streamlined and fun development proper will be.

jlrdw's avatar

I still use my own auth. Laravel doesn't force you to use the built in. Ask yourself why is there built in auth. Imho, because of lazy developers wanting more and more rather than writing their own.

I learned a lot from OWASP and Chris Shirley articles.

I suspect some people (lazies) want laravel to mow their lawn.

Laravel is a good (flexible ) framework but I sure liked version 5.1 better than latter versions.

Oh, and if the built in auth is so easy to implement why are forums flooded with auth questions.

Next

Please or to participate in this conversation.