Get user id from session - laravel 5.3 authentication - laravel

I have fresh Laravel 5.3 installation. Just used the php artisan make:auth
to get started with built in auth functionalities. All works fine, and after login the Auth::check() returns true, Auth::user() return the user's data and Auth::id() gives the logged in user's id.
What bothering me is that when I have only this line
$userId = Auth:id();
in my controller's action (and no other code elsewhere associated with Auth) in the Debugger panel's "Queries" tab I see the following query
select * from `users` where `users`.`id` = '34' limit 1
This extra query is highly undesirable to me (especially the select all part), as I need the user's id to make a query, selecting specific fields from users table, as well as to join it with another tables. For performance reasons I do not want to do double query.
So, is there a way to tell Laravel to save the logged in user's id in session(if it is not being saved) and get the id of the logged in user directly from session - without making any query to the database.
EDIT: I understand that after first Auth::user() call, the subsequent calls will not make requests to the database, however it is pointless, why make select * query, if I will need only some columns from the database. At least is there a way to tell Laravel to select only specific columns, instead of select * ?
Thanks

You don't need to execute another query. Use this object to get other properties:
auth()->user()->name

Related

Larvel Scout scoped to Logged in user via Auth::user() not working | Issues or technique wrong

Basically I have installed Laravel Scout with TNT Search, all of the configs are correct and they work, I even got a nice search bar to work with an ajax workflow
But the results from the models are from the entire database collection where as my requirement is only to show results of record of records created by the user who is currently logged in session
The models are related via Eloquent Relationships, they work when access normally via the Auth::user() method but the scout search seems to not be attached to any of the models via the Auth::user() example:
App\CourtCase::search($request->q)->get();
The above works but will return any result in the model (and underlying table) without any regards to if the record is owned or related to the user logged in. My intention is however
Auth::user()->courtcase()->search($request->q)->get();
The error i get is the following
message Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::search()
exception BadMethodCallException
file /home/vagrant/code/legistant/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php
Clearly this is because Laravel Scout is not attached or available via the Auth::user() method, I can write code to filter the results after they are returned, but imagine the over head of results before being scope by user, it seems like a waste of all that querying, is there a way to scope to user then use Laravel scout search similar to Auth::user()
Can modify the Auth behavior to attach scout, will it be overwritten using a composer update of Laravel?
So as of 05/05/2019
Laravel Scout does not have a method of scoping queries to Auth user related models, because honestly it is a quite difficult logic to process, especially because the relationships are arbitrary and the keys can be different, a scoping function built internally or externally would have the same computational cost, there is no optimizing here
$results = App\CourtCase::search($request->q)->where('lawyer_id', Auth::id())->get();
This is how I solved it, by attaching a where condition to the search result where it will only show details matching the key, if you are modifying existing code of an application, remember initially scout might show cached results that don't match the filter, which confused me until I refreshed the code
Better code is welcome

Getting the user by password reset token in Laravel without explicitly writing SQL query

I am developing a Laravel application. Now, I am trying to customise the password reset feature. I am trying to get the user by password reset token. I looked at the underlying database schema. There is a table called, password_resets. It has email, token and created_at columns. I can get the email of the user by token from that table. The thing is since there is no model created for that table, I will have to write the SQL query manually like this.
DB::select('SELECT * FROM password_resets WHERE token=?', [ $token ])
or the query builder
DB::table('password_resets')->where('token',$token)->first();
But I am trying to avoid using manual query. Is there a way to get the user by password reset token without writing manual SQL query?
DB::table('password_resets')->where('token',$token)->first();

Vue.js - Laravel User Id

Im working on a project to learn Vue.js with Laravel.
I created a simple tasks application, where its possible to create, modify, mark as done, and delete tasks.
I wish to make it user individual, so i ran artisan make:auth to create the auth template.
Added column : user_id to tasks table.
In the Index method of TaskController instead of -
return Task::all();
I tried to do -
return Task::where('user_id', Auth::id() );
but its not working as I wish...
If instead of Auth::id() I put 1 for example, it does return the tasks for user id 1.
Can anyone help me out?
Check in your code that Auth::id() is actually returning the user's ID - it's likely that your user isn't authenticated and is therefore returning null, so the query doesn't work as you expect.
Also, if you set up your associations correctly (that is, a user hasMany tasks) then you could simplify the code by using the association instead.
return Auth::user()->tasks;
// Achieves same result as...
return Task::where('user_id', Auth::id())->get();

How to keep session id after login in Laravel 5.1

I been using my session id to identify all the items that are added to a shopping cart temporary items table.
What I didn't know is that once the user login into the system the session id changes so I can't query the temporary items table anymore as there is no products containing the new session id value.
I am using file session driver and I was thinking to use db sessions but I think it will be exactly the same.
Any ideas on how to keep the session id after login?
Instead of using user's session_id you can store the cart items in a separate session key.
Like so -
Session::put('cart.items.0', $item_id);
Now you can access it as -
$cart = Session::get('cart');
Not exactly what you asked for, but to me this seems like a better way.

Storing remember_token to a separate table than users?

is it possible to set another table & column to store my remember tokens? I know that the framework tries to automatically find a remember_token column in my "users" model, but I want to store it separately from users. Is there a way to configure my default tokens table? Thank you
P.S - I'm using laravel 5
First, you need to create separate model for storing remember tokens and define a relationship on your User model like so
public function rememberToken() {
return $this->hasOne('RememberToken');
}
Then you need to override methods on your User model, originally defined in Authenticatable trait. Override getRememberToken() and setRememberToken() methods. You will also need to override getRememberTokenName() as it is used in where clause in EloquentUserProvider::retrieveByToken() see EloquentUserProvider line 60. In order for this to work properly you probably have to add global scope to your User model to join remember_tokens table on every query, and return 'remember_tokens.token' from getRememberTokenName() method.
Think twice as it seems more trouble than it is worth. Why would you want to store your tokens separately anyway?
I believe the way Laravel works uses a seperate column in the users table to store a single remember_me token. From my understanding it seems that logging out resets this token regardless of storing the token in a cookie (correct me if I'm wrong).
https://github.com/laravel/ideas/issues/971
If you log in with remember_me checked on your personal computer,
then again on your phone,
and maybe again with any other device,
then finally the act of signing out on any device using the remember_me token or not will reset this token in the DB.
If Laravel had a separate table, able to remember each device, it might solve the problem.

Resources