Laravel blade: Access method inside User model for authorized user - php

Authorized user info can be accessed in blades using auth()->user()->info.. , also other users info by App\User::where('id' , someid) , but how to call methods inside User Model for authorized user?
What i tried:
App\User::where('id' , auth()->user()->id)->MyMethod(another-user-instance); //Error: undefined method
App\User::MyMethod(another-user-instance): //Error: Wrong call, Its not static method!
App\User->MyMethod(another-user-instance): //Error: What? Unexpected ->
I have a Post model that is connected to User model using belongsTo, I can easily access my method in User by $AnyPostInstance->BelongToUser->MyMethod(another-user-instance) , but i don't know how to handle it for authorized user.

Well, first of all, calling the following is redundant:
App\User::where('id' , auth()->user()->id)
You're accessing the existing User, via auth()->user() to get its id and query for the exact same User. Don't do that.
Secondly, you need to use ->first() if you're calling App\User:
$user = App\User::first()->myMethod();
If you don't call ->first(), then you're accessing the Builder class, which doesn't have a myMethod() function.
So, ways to access:
auth()->user()->myMethod();
// This will access the currently logged in User
App\User::first()->myMethod();
// This will get the first User from the database
App\User::where("id", "=", $someUserId)->first()->myMethod();
// This will return a specific user matching `$someUserId`

You should do something like this:
App\User::where('id' , auth()->user()->id)->first()->MyMethod(another-user-instance);
The line above can be replaced with this one:
auth()->user()->myMethod(another-user-instance);
Hope it helps.

Related

Problem with accessing global variable in Laravel application

I am trying to make a global variable in AppServiceProvider.php that I will need throught my whole application meaning in all blade files. This variable is $profile which gets the profile data from user and displays them in blades. I made it so when I am on my profile it shows authenticated user which is me and it is fine (in url is like this profile/Authuser), that Authuser is username from database. Problem is when I go to some other profile then I get error undefined username (in url profile/Someuser). I need help on to get that username in AppServiceProvider.php. Problem is in that $username in service provider. I don't know how to pass it in there globally. Any help is appreciated. Here is my code.
AppServiceProvider.php
public function boot()
{
$profileId = $this->getIdFromUsername($username); // Here is problem, I don't know how to get that username
view()->composer('*', function ($view) {
$view->with('profile', Auth::id() ? UserProfile::profileDetails($profileId, Auth::user()->id) : []);
});
Builder::defaultStringLength(191); // Update defaultStringLength
}
public function getIdFromUsername($username)
{
if ($user = User::where('username', $username)->first()) {
return $user->id;
}
return abort(404);
}
web.php
Route::get('profile/{profile}', 'UserProfileController#showProfile')->name('profile.show');
I believe you are over complicating yourself.
If I understand your app. A user has a Profile correct?
Go to your User Model and create a relation between User and Profile
public function userProfile()
{
return $this->hasOne('App\UserProfile');
}
With that, the profile will follow the user, and you don't need to be passing it around.
If you want the Profile for the current User.
Auth::user()->userProfile();
If you want the profile of another user then
$owner = User::where('username', $username)->first();
$owner->userProfile();
Basically you can have access to the profile of your logged in user, or any other user easily by just finding the user you want.
Now, if you really wish to have a Model in every view, you are placing it in the wrong place. You see, Service Providers are intended to tie things up, not to get data. What you are probably thinking about is a View Composer that you do tie in with a Service Provider, but the actual data comes from the Composer itself. You can learn more about View Composer in the Docs. https://laravel.com/docs/7.x/views#view-composers
View Composers are just one way of doing it, a quick google search brought up this question which offers 3 additional alternatives to the view composer.
How to pass data to all views in Laravel 5?
Hope that helps.

Laravel - Get the Authenticated users

I have a navbar where I try to display some stuff depending if the user is authenticated or not.
So I have a login form, when I axios.post('/login') with the email / password, and I deal with the potential errors.
I have also a method in my UserController to get the authenticated user (if there is one) via Auth::user() like the docs says, but this methods always returns an empty object ...
public function getUser() {
$user = Auth::user();
Log::info($user);
return $user;
}
This methods always returns me a [2018-06-17 16:29:26] local.INFO:
But the stranger things (like the TV show) is where I try to go on my '/admin' routes, my middleware use also the 'Auth::user()' to determines if the user's role is 'user' or 'admin', that 'Auth::user()' methods returns me well the user ...
I am stuck ...
Please, if someone has experienced the same issue, let me know how to solve it, or if someone want to see more code, let me know as well I'll be glad to show you more proof.
Thanks,
public function getUser() {
$user = Auth::user()->name;
return $user;
}
Use Auth::user()->name; to return your user name on navbar.
You have to provide further info to Log::info(), Something like the name or id of the $user->name, $user->id.
Further more you can use that id, Search with it and get the info of the user.
You should have a proper pattern for the log, By pattern i means proper logging. Passing the whole object $user will not work.
Hello you must use this syntax on laravel version 8 and more
auth('api')->user()->id
api will be used when you have an api if you are on a web version you will use
auth('web')->user()->id

How do I get the logged in user's id in symfony 4?

The user can log in, but i need his id to show his profile. Since i'm working in symfony 4, the many possible answers i've found were obsolete.
https://symfony.com/doc/current/security.html#retrieving-the-user-object
After authentication, the User object of the current user can be accessed via the getUser() shortcut (which uses the security.token_storage service). From inside a controller, this will look like:
public function index()
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
}
The user will be an object and the class of that object will depend on your user provider. But, you didn't tell us what user provider you are using, so I have no way of telling you, beyond this, how to get to the id itself.
One other way to get the user:
An alternative way to get the current user in a controller is to type-hint the controller argument with UserInterface (and default it to null if being logged-in is optional):
use Symfony\Component\Security\Core\User\UserInterface\UserInterface;
public function indexAction(UserInterface $user = null)
{
// $user is null when not logged-in or anon.
}
This is only recommended for experienced developers who don't extend from the Symfony base controller and don't use the ControllerTrait either. Otherwise, it's recommended to keep using the getUser() shortcut.

Trying to Authenticate user without password in Laravel

I am trying to implement the login without password in laravel application but it shows an error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, string given
And the code i am using is:
$checkUser = 'manish.arora4926#gmail.com';
Auth::login($checkUser, true);
Please help me to resolve this issue.
Considering your email column name is email, try
$user = User::whereEmail('manish.arora4926#gmail.com')->first();
Auth::login($user)
or
Auth::loginUsingId($user->id);
If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. Of course, the App\User model included with Laravel already implements this interface:
$checkUser must be eloquent instance. so you need to access eloquent before authenticate user
$checkUser=App\User::where('email','manish.arora4926#gmail.com')->first();
Auth::login($checkUser, true);
in case you know id of user just using login using id
Auth::loginUsingId(1);
// Login and "remember" the given user...
Auth::loginUsingId(1, true);

Why Am I Able to Use user() method in laravel, without even defining it

I do have a UserController and User Model in my Laravel 5 source.
Also there is one AuthController is also Present (shipped prebuilt with laravel source).
I would like to query data from db in my blades making use of Eloquent Models.
However, Neither in my User Model (Eloquent ) nor in any of the controller, the user() method is defined. even then, I could use it in my blade by accessing it from Auth class. why?
For example,
in my blade, {{ Auth::user()->fname }} works. it retrieve the data fnamefrom my users table and echo it.
What is the logic behind it, and can i emulate the same for other db tables such as tasks?
Whenever you do it automatically or manually some like this
if (Auth::attempt(['email' => $email, 'password' => $password]))
{
}
The selected User's Data will be stored in the storage/framework/sessions
It will have data something like
a:4:{s:6:"_token";s:40:"PEKGoLhoXMl1rUDNNq2besE1iSTtSKylFFIhuoZu";s:9:"_previous";a:1:{s:3:"url";s:43:"http://localhost/Learnings/laravel5/laravel";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1432617607;s:1:"c";i:1432617607;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
The above sessions file doesn't have any data and it will have the data such as user's id, url, token in json format.
Then whenever you call the {{ Auth::user()->fname }} Laravel recognises that you're trying to fetch the logged in user's fname then laravel will fetch the file and get the user's primary key and refer it from the user's table from your database. and you can do it for all coloumns of the users table that you have.
You can learn more about it here
This user function is defined under
vendor/laravel/framework/src/Illuminate/Auth/Guard.php
with following content :
/**
* Get the currently authenticated user.
*
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method because that would tremendously slow an app.
if ( ! is_null($this->user))
{
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveById($id);
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();
if (is_null($user) && ! is_null($recaller))
{
$user = $this->getUserByRecaller($recaller);
if ($user)
{
$this->updateSession($user->getAuthIdentifier());
$this->fireLoginEvent($user, true);
}
}
return $this->user = $user;
}
this Guard.php has more functions defined in it which we use every now and then without even knowing where they are coming from
It works because Laravel comes with decent authentication.
Auth is the authentication library and has plenty of features like this, check out the documentation!

Categories