funfelfonfafis
funfelfonfafis

Reputation: 187

Laravel. I can't read the data from the column

I have a problem. Needs to get the first date of creation of data in the table by the currently logged in user.

Working example:

$howMuchIPlay = Game::all('user_id')->where('user_id', '=', Auth::user()->id)->count();

Not working example:

$firstVoteInGame = Game::all('created_at')->first()->where('user_id','=', Auth::user()->id);

When I use count() function I get value 38. This is all the rows for the user, but I want to get only the earliest (first). How can I do this?

Sorry for my english and thank you in advance for help.

Upvotes: 0

Views: 530

Answers (4)

Radical
Radical

Reputation: 1073

Your not working example, $firstVoteInGame = Game::all('created_at')->first()->where('user_id','=', Auth::user()->id);, starts off with Game::all('created_at').

What this means is that all Games are returned, but these are limited to the 'created_at' column only (see the documentation here).

Since you're limiting your result to the 'created_at' column, Eloquent will now not be able to compare the 'user_id' columns to the authenticated user id.

In addition, even if you were to select all columns (by performing Game::all()), you are calling ->first() after which you only have the first row remaining.

You say you want to

get the first date of creation of data in the table by the currently logged in user.

This would thus by done by:

$firstVoteInGame = Game::where('user_id', Auth::user()->id)->orderBy('created_at','asc')->first('created_at');

Upvotes: 1

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

Why you use 'created_at' for ordering as easy/correct way is use primary key, Because you can just do:

$firstVoteInGame = Game::where('user_id','=', Auth::user()->id)->orderBy('id', 'desc')->first();

You can try, if you still want 'created_at':

$firstVoteInGame = Game::where('user_id','=', Auth::user()->id)->orderBy('created_at', 'desc')->first();

TIP - The Eloquent all method will return all of the results in the model's table so avoid to use it with first method

Upvotes: 0

Tschallacka
Tschallacka

Reputation: 28742

You got the order wrong.

You should first limit by user Id.

Then order by created at in descending order so oldest is on top. Or if you want the newest, order by 'desc' instead of 'asc'

Then get the first.

Game::where('user_id','=', Auth::user()->id)->orderBy('created_at','asc')->first();

What you did was:

Get all records from database in a collection.
get first possible record from collection at index 0
limit a model object by a where query(it would fail here since you were in a model object, not a collection or query builder instance);

Upvotes: 1

Dees Oomens
Dees Oomens

Reputation: 5082

$firstVoteInGame = Game::where('user_id', '=', Auth::user()->id)->oldest()->first();

This will get the earliest (oldest) record from the current authenticated user.

Upvotes: 2

Related Questions