Laravel Query Builder in Lumen - laravel

When I use Laravel's query builder for my Lumen application with MySQL database, it does not work as expected. I used:
$itemid = DB::table('table1')->where('UserID','=',1)->pluck('ID');
This only returns one value. What is the mistake here?

Try
$itemid = DB::table('table1')->where('UserID','=',1)->get()->pluck('ID');
Here you can read more about why this happen when you use pluck on query
Pluck together with first using Query builder
Update:
I forget that DB::table returns array, so:
$items = DB::table('table1')->where('UserID','=',1)->get();
$itemsById = array_pluck($items, 'ID');

Use first instead of get as get return array.
$itemid = DB::table('table1')->where('UserID','=',1)->first()->pluck('ID');

Related

Laravel 7 Query with() and using Where()

Hey guys I have a query that looks like this
$query = Transaction::with(['customer', 'merchant', 'batch'])
->select(sprintf('%s.*', (new Transaction)->table));
I need to filter the transaction based on the iso_id that belons to the current user logged in.
$query = Transaction::with(['customer', 'merchant', 'batch'])
->select(sprintf('%s.*', (new Transaction)->table))
->where('merchant.iso_id', '=', auth()->user()->isIso());
The iso_id I need to compare to, is inside the merchant table
auth()->user()->isIso() returns the correct iso_id if true or sends false if not
So my first try at this was to use where('merchant.iso_id', '=', auth()->user()->isIso())
But that returns that the column does not exist because for some reason, it's not switching from the transaction model to the merchant one.
I am not sure how to use the stuff inside with() as a selector for my where()
Any help would be appreciated!
Try using whereHas to add the constraint:
$query = Transaction::with(['customer', 'batch'])
->whereHas('merchant', function ($q) {
$q->where('iso_id', auth()->user()->isIso());
})
->select(sprintf('%s.*', (new Transaction)->table))
->get();

Laravel - How to Transform Raw Query to Eloquent in Laravel

How do I transform my raw query to Laravel Eloquent
I want to transform
$games = DB::table('game_point')
->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
->paginate(15);
to
$games= new GamePoint();
To try this,
Here you change your date format in Date() function.
$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);
foreach($data as $key => $val){
$data[$key]->created_at = Date('Y-m-d',strtotime($data[$key]->created_at));
}
You can directly change it by using date() in blade or in controller depend upon your usage.
try the following code
$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);
Or In the blade or contrller you can use it just paste it where you using inside foreach
date('Y-m-d', strtotime($user->from_date));
Or you can use carbon which is already included in laravel for working with date and time.
You can read about this package here
try below:
$games = GamePoint::paginate(15);

How to paginate and sort results in Laravel?

I need to paginate the results and sort them using sortBy(), without losing the pagination links. I also need to use a resource to return the results.
$sorted = Model::paginate(10)->sortBy('name');
$results = \App\Http\Resources\MyResource::collection($sorted);
Doing this breaks the pagination links (I get only the data part).
$paginated = Model::paginate(10);
$results = \App\Http\Resources\MyResource::collection($paginated);
return $results->sortBy('name');
This also doesn't work.
Any ideas?
Using the getCollection() and setCollection() method in the paginator class, You can update the pagination result without losing the meta data.
$result = Post::orderBy('another_key')->paginate();
$sortedResult = $result->getCollection()->sortBy('key_name')->values();
$result->setCollection($sortedResult);
return $result;
I think you can sort the results first, and then paginate
$sorted = Model::orderBy('name')->paginate(10);
I've solved the problem with this solution:
$sorted = Model::get()
->sortBy('example_function') //appended attribute
->pluck('id')
->toArray();
$orderedIds = implode(',', $sorted);
$result = DB::table('model')
->orderByRaw(\DB::raw("FIELD(id, ".$orderedIds." )"))
->paginate(10);
I've appended example_function attribute to the model, to be used by sortBy. With this solution I was able to use orderBy to order by an appended attribute of the model. And also I was able to use pagination.

Can I put a collection or array into the where clause on laravel eloquent?

$collection=["c","a","f","h","j","o","k"]
$total_sums=Models::select('count')->whereIn('class',['c','a','f','h','j','o','k'])
->get()
->sum('count');
can I use variable $collection like this?
$total_sums=Models::select('count')->whereIn('class',[''.$collection.''])
->get()
->sum('count');
You can use both.
whereIn() accepts both Array and a Collection.
You just simply pass it as a second parameter.
$array = ["c","a","f","h","j","o","k"];
$collection = collect($array);
$total_sums=Models::select('count')->whereIn('class', $array)
->get()
->sum('count');
// works
$total_sums=Models::select('count')->whereIn('class', $collection)
->get()
->sum('count');
// also works!
No because $collection is already an array. When you try to concatenate it to a string, I believe your query will look like the following...
select count from models where class in ('Array');
What you probably actually want to do is...
->whereIn('class', $collection)

Laravel Eloquent Pagination orderBy first

I have a simple pagination from my model User:
$users = User::paginate(15);
Unfortunately, it returns the results ordered by id or something.
I want to order the results ASC first and then paginate on them.
Can't find any way to get that working in combination with the paginate() method, like:
$users = User::orderBy('username', 'asc')->paginate(15);
Any idea?
Thanks
I already test it like your code. It works. Can you give the error.
Route::get('/view-tags', function()
{
$tag = App\Tag::orderBy('name', 'asc')->paginate(5);
dd($tag);
});

Resources