Can I convert array of models into collection of models? - laravel

In Laravel 8 Backend app with output
$var->toArray())
if $var is collection of models, then array of model values is outputted
But if $var - is array, which generated as :
$permissions = Permission
::orderBy('name', 'asc')
->get()
->map(function ($permissionItem) use ($userPermissions) {
return $permissionItem;
})
->all();
$permissions - would be array of models. Can I to convert it into collection and use toArray() to it ?
Thanks!

Don't call all on your Collection. Calling all gives you the array of items. Just don't call all if you want to keep it as a Collection.
If you are not in control of that call then you would need to make a Collection from your array and then do what you want with it:
collect($var)->toArray()

Related

Error Call to a member function where() on array Laravel

I want to do filtering from the data that I display, but there is a problem when I add where to my data.
the plan in the future I want to add if isset $request name, date and others. but was constrained at this one point.
Thank you for helping to answer in advance
$matchs =Matchs::where('type', 'sparring')->where('status','Pending')->whereNull('deleted_at')->get()->toArray();
$data=[];
foreach ($matchs as $key) {
$lawan = Matchs::where('id', $key['id'])->first()->ToArray();
$pertandingan = Sparring::where('match_id', $key['id'])->first()->ToArray();
$dua_arah = MatchTwoTeam::where('match_id', $key['id'])->first()->ToArray();
$tim = Team::where('id', $dua_arah['home_team'])->first()->ToArray();
$transfer['name']=$tim['name'];
$transfer['city']=$lawan['city'];
$transfer['field_cost']=$pertandingan['field_cost'];
$transfer['referee_cost']=$pertandingan['referee_cost'];
$transfer['logo_path']=$tim['logo_path'];
$transfer['nama_lapangan']=$lawan['nama_lapangan'];
$transfer['date']=$lawan['date'];
array_push($data,$transfer);
array_push($data,$pertandingan);
}
$data->where('name', 'LIKE', '%'.'football'.'%')->get()->toArray();
$data = array_search('football', array_column($data, 'name'));
$tittle="Sparring";
return view('mode.sparring',[
'tittle' => $tittle,
'data' => $data,
]);
You are trying to call where in an array which is not possible.
As you can see in the first line of your code you are calling where method in your model class. Like Matchs::where('type', 'sparring'), this is possible because Matchs is a Model class.
Now you can run where even if you are using array. You can convert that day in collection and then use array on that collection.
As below:
collect($data)->where('name', 'football')->toArray();
Here collect() will convert the $data array to collectio and then run the where() method in collectio then toArray() will change it back to array. But unfortunately there is no like operator possible in collection class. See the list of available method in Laravel collection here: https://laravel.com/docs/8.x/collections#available-methods
There is a way to do what you are trying to do. As far as I understand you want to filter the Matches where the Team name has footbal in it. You can do it like this:
Matchs::where('type', 'sparring')
->where('status','Pending')
->whereNull('deleted_at')
->whereHas('team', function($team) {
return $team->where('name', 'LIKE', '%'.'football'.'%')
})
->get()
->toArray();
So, here we can get the only those Mathes that has the Team that has the name contains football.
Few suggestion for you as seems you are new in Laravel:
Model name should be singular instead of plural, so the model class Matchs should be Match. Your name for team's model is Team is correct.
Avoid using toArray() because you won't need it. When you call get() it will return object of collection which more readable and powerful then array in most cases.
The code I suggested to use the like using whereHas will only work if you have propery defined your team relation in your Matchs class. So, defining your relationships in model is also important. If you do so, you don't even need the for loop and all those where in other model in that loop. You can do it in one query with all the relationships.

read manipulate and write to the db in Laravel

I am going to read the data by query, manipulate some values and write it back to the db. I use the code below but I get an error.
$data = DB::table('users')->get()->toArray();
foreach ($data as $d){
$d->id = $id+100;
DB::table('users')->insert($d);
}
Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array,
but the input is already an array. Do you have a better solution for this?
Ok. let's explain this, what ->toArray() actually did is converting the whole collection to array not casting the selected records to array so if you dd($data) you will find it's an array of objects not array of arrays, so what you need to do is to cast each record in the selected records like so
$data = DB::table('users')->get()->map(function ($user) {
return (array) $user;
})->toArray();
as i said
->toArray() - this will convert the whole collection to array
(array) $user - this will convert the selected record to array
you can simply use increment function
DB::table('users')
->increment('id', 100);
more info : laravel docs

Laravel: Getting the first item after querying a collection already?

I need access to an entire collection but I also want to pull out and use the first item on the collection. Can first() be used outside the context of a query like this to get the first item?
$items = Item::with(['name'])->where('prod_num', '=', $num)->get();
$firstItem = $items->first();
Where you query a Model using Eloquent, as you are doing, it returns a Eloquent Collection.
Eloquent Collections extend Collections (https://laravel.com/docs/6.x/eloquent-collections#method-intersect), which have first() method available. So, you can use it.
Ref: https://laravel.com/docs/6.x/collections#method-first
Yes, you call the first() method to get the first element in the collection.
Since you called ->get() in $items it will return a collection, so you can call the first() method in it.

Laravel Eloquent ORM - How to get the all the properties of afrom/of a collection in a array?

$user_emails = ["email_1#domain.com", "email_2#domain.org"];
$users = Users::whereIn("email", $user_emails);
The table for users also has a phone column for each user. What's the best way to get a list/array of the phone number as an array?
$users->all()->phone(); // Like (which is not correct)
Try to use get() like :
$users = Users::whereIn("email", $user_emails)->get(['phone'])->toArray();
Or also pluck() like :
$users = Users::whereIn("email", $user_emails)->pluck('phone')->all();
Hope this helps.
Use pluck method to fetch a specific column's values and then use toArray on returned Collection object to get results as an array.
$phoneNumbers = Users::whereIn("email", $user_emails)->pluck('phone')->toArray();
You can get all column data with get()
Example:
$user = $user::where('email', $user_emails)->get();
You can get the list with foreach loop method.

How to convert an eloquent query into an array

I have the following eloquent query which uses a many-to-many relationship to grab all groups associated with the authenticated user.
$usergr = Auth::User()->usergroup()->get();
Pivot table
ID|user_id|group_id
1 |1 |2
2 |1 |3
I would like to convert this to an array of group_id. So fare it is a collection object however I need this converted to an array to be used on another query.
I have this so far:
foreach ($usergr as $obj)
{
$array[]= (array) $obj;
}
The query I for teh array is below:
$usergrsub = DB::table('group_subjectlist')->whereIn('group_id', $array)
->select('subjectlist_id')
->distinct()->get();
However the query above is not recognising the $array variable
(I use version 4.2)
In this particular case, the lists() function may do what you want.
Auth::User()->usergroup()->lists('group_id')
Most result objects returned by Laravel's builders have a toArray() method that will convert the object into an array.
The whereIn method expects an array of values, but the result of get() will be a collection of objects, which if converted to an array will be an array of associative arrays.
If you need the get() result only for the whereIn query you should use lists('group_id') instead of get(). Otherwise consider using pluck('group_id').

Resources