Reputation: 113
I'm (learning Laravel and) building a blog based on Laravel 5.8. Right now I've seeded some fake user into the database for testing purposes. Because the users are random, I want to show the username of a user in a blade template (my layout template).
What I've done seems to be wrong. I've set the session variables in my routes/web.php file:
Use App\User;
session(['user' => User::first()]);
session(['user_id' => User::first()->id]);
Route::get('/', 'PostController@index');
In my blade file I access them:
<h2 class="subtitle">
My self-made blog with Laravel (Login: {{ Session::get('user')->email }} )
</h2>
At first it was working fine, although i'm not sure whether it's the right way to do. But now i've cloned my project and tried to migrate the database (in a empty database), i get several errors:
The laravel.users table does not exist.
So i figured out, that setting the session variables based on database values is not possible at that place of my routes/web.php file.
Where or how can i set these session variables so it would only set the variables once (if possible) and without coming to my empty database problem?
Thanks.
Upvotes: 1
Views: 377
Reputation: 5582
you can use Laravel Auth::loginUsingId(1);
that will login user by user id which you will specify. In that case you have no need to set details in Session.
For reference you can check it out here
But if you want to use session then Middlewares are the best place to do these types of things.
You just need to create new Middleware and add you code here. After that you can add this middleware to those routes on which you want to use this.
Upvotes: 2
Reputation: 33186
The web.php
routes file is always loaded by Laravel, even when running migrations. So when you try to migrate your application, it's trying to load the first user from the database in your web.php
file. And because the users table does not yet exist, you get an SQL error.
This code should indeed not be placed here, and instead you should take a look at middelwares.
Even better would be to use the built-in authentication functionality from Laravel. This provides you with loads of functions to manipulate and fetch the current signed in user.
Upvotes: 0