laravel eloquent lists - Sorting A List Of Column Values - laravel

Using laravel and I'm creating a select box on a form. I've been using the helper to create the select box and all is working fine.
I retrieve the data for the select box from a database and use the following to retrieve the data:
$data = model::lists('name','id')
Again all works ok and this returns the expected array
My problem though is I can't seem to sort this list - i've tried adding orderBy() but no joy.
Other than using a native php function is there a laravel method to sort a list?

You can put whatever you want, and then list it. I mean:
model::orderBy('orderByColumn')->lists('name', 'id');
As long as lists is the last method in the chain, other methods works just fine.
Starting from Laravel version 5.3 lists is going to be deprecated, use pluck instead:
model::orderBy('orderByColumn')->pluck('name', 'id');

You can try:
$data = model::select('name','id')->orderBy('name');
If that doesn't work, toss a ->get() on the end:
$data = model::select('name','id')->orderBy('name')->get();

when I
dd(YourModel::pluck('name', 'id'));
I see it is Collection Class so I found collection laravel and then I found method sortKeys()
so I do:
YourModel::pluck('name', 'id')->sortKeys();

Related

Query database table using LIKE in Laravel

I am trying to query a table using where like :
Auth::user()
->friends
->where('friend.first_name','LIKE','%'.$firstName.'%')
->all()
The query does work properly without using the LIKE statement only when i add the LIKE keyword it doesn't return any results.
Using all() will work without the builder where() statement.
When grabbing data using the query, use get() instead:
Auth::user()->friends->where('something','LIKE','%'.$something.'%')->get()
I think you are confused between a laravel relation and a eloquent collection. First let me go straight to answer, you would have to do
Auth::user()
->friends()
->where('friend.first_name','LIKE','%'.$firstName.'%')
->get()
To explain what's wrong with your code, ->where('name', 'Like', '%something%') This is a query builder method. You have to use it on the query builder, or Before you actually retrieve the model / model collection.
Auth::user()->friends()
This would give you a relation Illuminate\Database\Eloquent\Relations\HasMany that you can apply where like on.
Auth::user()->friends
This will return you a Illuminate\Database\Eloquent\Collection. And yes, it is a collection, so you will have to use collection method. Take a look at the where method for collection. You can see it only support key => value pair. It does not support "LIKE"
The where method filters the collection by a given key / value pair:
If you want to use achieve a "Like" on collection, you can probably use the filter method, which support custom callback.
The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:
To conclude, when you define a friends "HasMany" relation on User, you have two way to retrieve it.
If you want to apply additional query builder method, you need to use user->friends() which do not return you data, it return you a relation that you can use query builder method. Once you do user->friends, it get you a collection. You cannot apply query builder on that anymore. So basically, user->friends is act the same way as user->friends()->get()
Don't Use all() and use get().
Auth::user()->friends()->where('something','LIKE','%'.$something.'%')->get()

Create pagination from groupBy in laravel 5.8

$payments = Payment::with('borrowerUser','collectorUser')
->get()
->groupBy('date_paid');
which gives me this result
My question is, is it possible for me to put a pagination in this scenario?
I already tried
$payments = Payment::listings()
->with('borrowerUser','collectorUser')
->groupBy('date_paid')->paginate(5);
and put {{$payments->listings()}} on my blade
but that doesn't work.
any suggestions? thank you in advance!
put this code in controller:
$payments = Payment::with('borrowerUser','collectorUser')
->groupBy('date_paid')->paginate(5);
put below code in blade file after for loop is completed
{!! $payments ->render() !!}
This is the must read content from the laravel documentation
Currently, pagination operations that use a groupBy statement cannot
be executed efficiently by Laravel. If you need to use a groupBy with
a paginated result set, it is recommended that you query the database
and create a paginator manually.
Documentation link
You can use orderBy clause after groupBy to get the result, but still it won't give you efficient results

Laravel Eloquent find and where return two different types?

When I use:
$myModel::find(1);
I'm completely fine using accessors, for example - that's because it returns an instance of the model?
And if I use
$myModel::where('foo', 'bar');
I can no longer access any accessors or model function, or even relationships on myModel Is that expected behavior and if it is - how should I execute a where query so I can keep using the model's relations?
you need to fetch the model.After that everything will work fine.
$myModel::where('foo', 'bar')->firstOrFail();

Eloquent model setRelation generating array instead of Collection

If you are doing $instance = $model->with('categories')->find($id); and after var_dump($instance->categories) it going to return Collection of categories.
But on the project I'm working on in some heavy queries, we are not using with and getting data with a combination of GROUP_CONCAT and CONCAT, like this:
\DB::raw('GROUP_CONCAT(DISTINCT CONCAT(categories.id, ",,", categories.name) SEPARATOR ";;") as categories'),
And then we are building relations manually parsing result and creating a relationship using $instance->setRelation($relation, $data) but for some reason, it's returning an array of objects instead of Collection.
There are also option to use setRelations() and this method returning Collection but I found if you have bidirectional relations it's creating recursion and working really slow. For example: if in User model we have set $this->hasMany('Comments') and in Comments model we have set return $this->belongsTo('User'); and after when we running setRelations() to manually build relations it is create nesting models with recursion (User->Comments->User and so on).
The third option is to not use setRelation() or setRelations() and just to manually create Collection, populating it and set to model. But in such case, it will not be set as a model relation.
Any suggestions on how to build manually in the right way (to create relation is same way eloquent creating with with).
Group return collection of collection so you have to remove the keys of first collection and for that you can use values function of collection like this
$instance->setRelation('relation', $data->values()->all());
Details https://laravel.com/docs/5.6/collections#method-values

How to get M:1 relation in Yii2

I am trying to get related model however i cannot seem to find correct documention. In yii 1.x i can do $jobsprocess->category0, but yii 2.x tell me to do $jobsprocess->getCategory(). This does not return a model but an ActiveQuery. How can I return a model object?
In your query use $model = YourModel::find()->with(['category])->all().
All relations using the getRelation() functions can be access with the with() function, but without the get and lowercase first letter.
You can then access the relational data with $model->category.

Resources