Getting last element of the Collection - laravel

guys, I'm trying to get the last element from the data returned to me but the problem is that it is throwing me an error which is
Call to undefined method Illuminate\Database\Query\Builder::last()
Here is my code
$last_saved_snapshot = \EnginePerformanceTestSnapshot::where('engine_performance_test_id', $id)->last();
Please tell me what is it that I'm doing wrong. Thanks
P.S I'm using Laravel 5.0

Try something like that:
$last_saved_snapshot = \EnginePerformanceTestSnapshot::where('engine_performance_test_id', $id)
->get()
->last();

The last method call is not working because namespace Illuminate\Database\Eloquent; does not have any last() method. The right way to do this is to do something like this:
$last_saved_snapshot = EnginePerformanceTestSnapshot::query()
->where('engine_performance_test_id', $id)
->orderBy('id', 'desc')
->first();
Otherwise, you need to get all items, since last() is part of the collection class so it expects a collection or array to be able to work and not a query builder. It is less efficient and a bad practice to fetch all data just for one.

I found another way to do it and that is:
$last_saved_snapshot = \EnginePerformanceTestSnapshot::where('engine_performance_test_id', $id)->orderBy('id', 'desc')->first();
This is working but if somebody can tell me why is the last not working then that would be a great help. Thanks

Try this, less code:
\EnginePerformanceTestSnapshot::
where('engine_performance_test_id', $id)
->latest()
->first();

Related

Add extra column to laravel select query

It may sound as a duplicate question. Please I have not found a working solution.I want to add additional field to my query in laravel but I am getting error. This is the php implementation
select id, "extra_column as type" from cases
have tried
DB::table('cases')
->select(['id'])
->selectSub(function($query){
$query->selectRaw('extra_column');
},'type')
->get();
but I keep getting error
You need to use like this:
DB::table('cases')
->select(['id', 'extra_column as type'])
->get();
Please try addSelect('extra_column as type').
DB::table('cases')
->select(['id'])
->addSelect(`<additional column>`) // We can able to use variable as well $value = 'extra_column as type';
->get();
I later found out the solution. the extra_column was missing a double quote
DB::table('cases')
->select(['id'])
->selectSub(function($query){
$query->selectRaw('"extra_column"');
},'type')
->get();
You can find that scenario in Laravel docs like so,
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
OR you can do something like this also:
DB::table('users')->select('name')
->addSelect('email as user_email');
and in case this triggers an issue as you told, please make sure that this column exists in your database.

Method Illuminate\Database\Eloquent\Collection::orderby does not exist

$posts = Post::all()->orderby('created_at','desc')->where('usr_id','=',session('LoggedUser'))->get();
return view('admin.profile',compact('userInfo' , 'posts'));
i am making a custom auth for a journal activity but i cant sort the content i shows this error
"Method Illuminate\Database\Eloquent\Collection::orderby does not exist. "
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();
True query like that. When you take all() already query done.
Change it to:
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();
you cant use all() and orderBy because all() does not allow the modification of the query.
I believe this might be because you typed orderby instead of orderBy (notice the uppercase). See laravel orderBy documentation if needed.
Plus, as mentionned by other, don't use all() if you need to do other thing (where clause, order by, etc) in you query.
Change the orderby to orderBy. This could be the reason you are getting the error.
$posts = Post::all()->orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->get();
return view('admin.profile',compact('userInfo' , 'posts'));
Or...
If you want to get specific number of posts you can do it this way to avoid using the Post::all
$posts = Post::orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->paginate(5);
return view('admin.profile',compact('userInfo' , 'posts'));
Yeah this is pretty confusing and just got me as well.
The actual problem isn't the capitilization typo (orderby versus orderBy) but rather the fact that you're using ->all() instead of just Model::orderBy()->...
The moment you use ->all() the object is transformed to another type of collection object and the normal methods one would expect do not exist.
In this case you should rather use sortBy().
See here.

Laravel I cannot pull a single row that is not contained in Query result

First I apologize for my bad english.
I want to get first category=1 posts and then, only one post not equal Posts.The code I wrote is below, is there wrong in my code, or I am sending an incorrect query because I use postgreSql.
$posts= Post::where('category',1)->get();
$onlyone = Post::where('id','!=', $posts)->first();
This should get you what you want...
$posts = Post::where('category', 1)->get();
$onlyone= Post::where('category', '!=', 1)->first();
If you actually have a collection of posts that you want to exclude you want to do something like Post::whereNotIn('id', $posts->pluck('id'))->first();

Undefined property: Illuminate\Support\Collection::$election_name in view

In the controller, I store some data in an array.Then I want to send it in myelectionlist.blade.php
$my_election=[];
$i=0;
foreach ($election_list as $election_list)
{
$my_election[$i]=DB::table('election')
->where('id','=',$election_list->election_id)
->get();
$i++;
}
return view::make('myelectionlist')->with('election_list',$my_election);
I check with
return $my_election
It works fine. But In myelectionlist.blade.php when I write
#for($i=0;$i<sizeof($election_list);$i++)
{{$election_list[$i]->election_name}}
#endfor
It does not work.
Undefined property: Illuminate\Support\Collection::$election_name
happens, How to solve the problem?
There's a combination of problems that I would fix in order to bring clarity to your code and explain to you the problem. First of all in your code you have:
foreach ($election_list as $election_list)
I'll rename the variable for you to see:
foreach ($foo as $foo)
So what this does is that inside the foreach loop you will get all the values one by one, like expected but every time you store it to the initial variable. And once you are done with the foreach or break out of it earlier the $election_list will have the last used value. It might have unexpected results if you're trying to use the same $election_list later again. So I would suggest to use a differet variable names perhaps like $election_list as $election
Next, it's a little bit unclear why you would track the $index of the new elements by yourself. Instead you could just push into the array like this:
$my_election[] = $newObj
Actual error message:
Now for the actual error message: ->get() returns a Collection. So in the end you have an array full of Collections. So inside the for loop when you do $election_list[$i] - this will actually be a Collection object instead of the Model and thus the exception.
->get() will always get you the collection. For example with methods like ->first() and find/findOrFail you would get a single model. These functions might also be more appropriate to use since we are requesting with and id anyway.
Additionally, if this question is not a simplified version of your code then what I think you should actually do inside the controller:
$my_election = DB::table('election')
->whereIn('id', $election_list->pluck('election_id')) // pluck will give all the id's
->get();
This way you have a Collection of models assigned to $my_election.

How to add dynamic 'where' to eloquent ORM with() relation

I'm, trying to do something like this:
$verfuegbarkeiten = Verfuegbarkeit::verfuegbar()->with('product', 'producer', 'producer.user', 'producer.user.ort')->where('product.kategorie_id', '=', $_GET['kat'])->get()->toArray();
I want to use a 'where' clause so i can only get the results where the 'product's attribute 'kategorie_id' matches the GET parameter. How can I 'where' on a relation? It's really important to me that this value can be dynamic, so writing a fix function in the related Model won't be a good solution.
Every hint appreciated
You want whereHas(), documentation here: https://laravel.com/docs/5.2/eloquent-relationships#querying-relations
For your example, that would mean something like this:
$kat = $_GET['kat'];
$verfuegbarkeiten = Verfuegbarkeit::verfuegbar()
->with('product', 'producer', 'producer.user', 'producer.user.ort')
->whereHas('product', function($query) use ($kat) {
$query->where('kat', $kat);
})
->get()
->toArray();
Although I might add that using $_GET is generally discouraged in Laravel.

Resources