Laravel Auth User - laravel

In my controller i'm doing
$user = Auth:user()->get();
dd($user);
This is giving me the list of all users from my database.
why?

The other answers either explain how to solve your problem but not properly why this happens.
The laravel documentation states (source):
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object.
With the full documentation found here, with API references here.
In essence, the get function here returns a collection and not the User object. The get method on an QueryBuilder executes a select statement.
With the following snippet we can see what queries get executed.
DB::enableQueryLog();
Auth::user()->get();
dump(DB::getQueryLog());
This will output:
DB::enableQueryLog();
Auth::user()->where('id', 1)->get();
dump(DB::getQueryLog());
This will output:
The first query will indeed output the expected user, the second query will grab the user class from the Auth::user() and select all rows from that table.
When we execute the 3rd and 4th query we can see that we once more first get the expected user, the 4th query however does also get a user (in this case the user with id 1). This is due too the where and not the Auth::user().
What we can conclude from these results is that the get takes into account all query builder functions but not the parameters of the supplied class.
If you use a get on an object it will only take into account the Class of that Object.
As too solve your problem the other questions where correct and you can use:
$user = Auth::user();
To fetch the user.

Because get return collection
Laravel Doc

Just remove get() to get single user data
$user = Auth:user();
dd($user);
in this case get() method return user collection object

You can auth user data by :
$user = Auth::user(); instead of using get();
Your user id is: {{ $user->id }}
Your first name is: {{ $user->first_name }}
Your last name is: {{ $user->last_name }}

return User::where('id', auth()->id())->with(['something'])->first()

Related

Laravel Query builder returning null

I am trying to run the query below but I keep getting null return.
$result = Order::with(['customers', 'team'])->where('customers_id','=', $custid)->select(sprintf('%s.*', (new Order)->table));
Then I changed it to
$result = Order::with(['customers', 'team'])->where(function($query) use ($cust) {$query->where('customers_id', $cust);})->select(sprintf('%s.*', (new Order)->table));
still returns null.
customers_id belongs to the orders table and references the customer's table. I am getting the $custid from the URL parameter.
If I replace $custid with an integer for example 3, it returns all orders for the customer with id 3. I have spent hours trying to resolve the issue. I have hosted on Heroku and localhost but nothing works.
Your problem is the way you're getting the url parameter. Put your url parameter in your method declaration.
Check the Laravel docs under Dependency Injection & Route Parameters here
public function index(Request $request, $custid) {

Laravel Illuminate\Database\Eloquent\Collection::createToken does not exist

After I create a new user I try to create token via
$user = User::where('user_id', '=', $userid)->get();
$user->createToken('name')->accessToken;
Then i got the following error:
Method Illuminate\Database\Eloquent\Collection::createToken does not
exist.
Thanks
You are calling for a collection of users when you use the get() method, which won't have the createToken method (which is exactly what the error message is telling you).
You need to call for a single User model:
$user = User::find($userid);
And then, assuming you have the createToken method on your User model, this should work.
EDIT per comments:
You may have some other issue that is preventing the creation of the token in addition to the original issue of the collection vs an object. Try to create the token first:
$user = User::find($userid);
$token = $user->createToken('name');
Then if you will either get an error (if your createToken method is incorrect, or the parameter 'name' is not correct, etc), or you will have the token, and can then draw the accessToken from the new variable, $token.
Like this:
$accessToken = $token->accessToken
Either way, this will give you the diagnostics to bug hunt.

Laravel - can't get model after deleting related model records

I have a function postShippingmethods in which I delete, update or create new shipping methods depending what the user specified in the form. It works like it should , except that if any methods are deleted, I get empty result when trying to retrieve the user model with the updated methods.
To delete methods, I first get the user:
$user = \App\User::where('id',$id)->with(['shipping_profiles' => function($query) {
$query->where('default', 1);
}, 'shipping_profiles.methods' ])->first();
I compare the stored methods to the ones in the request; if any are missing , they should be deleted.
This code does the deletion:
foreach($non_included_ids as $id){
$method = \App\ShippingMethod::find($id);
$method->suppliers()->detach();
$method->delete();
}
Then I get the user once again, to get the updated data:
$user = \App\User::where('id',$id)->with(['shipping_profiles' => function($query) {
$query->where('default', 1);
}, 'shipping_profiles.methods' ])->first();
^^ this works well if nothing was deleted, but for some reason if something was deleted, the above code will return nothing. And when I try to use the $user to retrieve data I of course get "Trying to get property of non object".
So can anyone explain why this happen and what I should do to get the user with the updated data?
Use a different variable name in the loop:
foreach($non_included_ids as $non_included_id){
Otherwise, the loop changes the value of $id and \App\User::where('id',$id) fetches the wrong user.

Laravel: Passing variable from Blade to relationship not working

I am trying to modify a Laravel relationship to return the related case against a question.
My question model has the following relationship entry:
/**
* A Question has one Case Detail
*
* #return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function casedetail( $caseId ) {
return $this->hasOne( 'App\CaseDetail' )->where( 'test_case_id', $caseId );
}
However, trying to access the casedetail from Blade using a variable like this:
{{ $Question->casedetail(2) }}
Is returning me the following error:
"htmlspecialchars() expects parameter 1 to be string, object given (View: /home/vagrant/Code/TestBench/resources/views/testcases/category_questions.blade.php)"
If I substitute $caseId for a specific number and remove the variable request from the method then my query works fine:
return $this->hasOne( 'App\CaseDetail' )->where( 'test_case_id', 2 );
Result:
{"id":1,"test_case_id":2,"question_id":1,"result_type":0,"result":"now what","tester_id":1,"attachment":null,"created_at":"2017-11-30 03:17:42","updated_at":"2017-12-04 06:57:40"}
I am trying to retrieve the specific CaseDetail from the database that relates to the question_id and test_case_id. So for each question, give me the related CaseDetail:
#foreach( $Category->Questions as $Question )
{{ $Question->casedetail( $TestCase->id ) }}
#endforeach
I think everything is correct. In this case, you calling relationship method. Every relationship method returns you object of a collection.
Might be a chance here blade need single property or string to print and method returns collection?
Have you tried like this:
{{ $Question->casedetail(2)->id }}
try to print single property hope it works.

Trying to get property of non-object error occurs in my controller

Was trying to call orders made by a particular user
from my database but get error from my controller reporting from controller..
Public function getYourOrders {
$order = Order::where('user_id','=',Auth::user()->id)->get();
return View::make('orders.show')->with('order',$order);
}
This is where the errorexception is reporting from
If you don't have a logged in user, Auth::user()->id would give you that error.
If you work with framework version 4.1.26+ don't use Auth::user()->id to retrieve user's id.
Instead use id method:
Auth::id();
it will take care of returning null if there's no logged in user and it will not execute unnecessary DB query (when using DB driver)

Resources