Reputation: 159
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.
Upvotes: 0
Views: 1411
Reputation: 2602
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.
Upvotes: 1
Reputation: 29278
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`
Upvotes: 1