Add extra column to laravel select query - laravel

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.

Related

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();

Laravel Eloquent duplicate distinct row

Let's consider the image above. I would like to show duplicated entries as one entry and also I want to show the sum of the "stock" column. In this case it should be 5722.
Is it possible to do it using Eloquent? Or what are the best ways to do it?
Not sure how your database / query is built but you could maybe use something like that:
Item::groupBy('item_name')
->selectRaw('*, sum(stock) as sum')
->get();
It will return a collection of Item with an additional “sum” field
This will group the result with same medicine and supplier name and sum up the stock.
$result = Model_Name::groupBy('medicine_name','supplier_name')
->selectRaw('*, sum(stock) as sum')
->get();
Try this. Hope it might help you.

Getting last element of the Collection

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();

Group By Eloquent ORM

I was searching for making a GROUP BY name Eloquent ORM docs but I haven't find anything, neither on google.
Does anyone know if it's possible ? or should I use query builder ?
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
Laravel 5
WARNING: As #Usama stated in comments section, this groups by AFTER fetching data from the database. The grouping is not done by the database server.
I wouldn't recommend this solution for large data set.
This is working for me (i use laravel 5.6).
$collection = MyModel::all()->groupBy('column');
If you want to convert the collection to plain php array, you can use toArray()
$array = MyModel::all()->groupBy('column')->toArray();
try: ->unique('column')
example:
$users = User::get()->unique('column');

Resources