how to make an eloquent result into an array Laravel - php

I want to combine two data search results into one array, I use array_merge but there is an array_merge() error:
Argument # 1 is not an array
How to turn $vendor's eloquent results into an array and combine it with $plucked?
$vendor = Vendor::find($id);
$vendor_detail = VendorDetail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_profile_value','vendor_profile_name');
$coba = array_merge($vendor,$plucked);
$plucked already an array
I think the problem here is that $vendor is not yet an array

You could do it like this:
$vendor = Vendor::find($id);
$vendor_details = VendorDetail
::select('vendor_profile_value', 'vendor_profile_name')
->where('vendor_id', $id)
->get()
->toArray();
$coba = array_merge($vendor,$vendor_details);
The get() method execute the query returning a Collection instance, in which you can call the toArray() method.
Side note
As far as I can see, you could make use of relationships and eager loading.
If you have a one-to-many relationship defined like this in your Vendor model:
public function details()
{
return $this->hasMany(VendorDetails::class);
}
Then, you could eager load the relationship like this:
$vendor = Vendor::with('details')->find($id);
// ^^^^^^^^^^^^^^
You could even just load the wanted fields:
$vendor = Vendor::with('details:vendor_profile_value,vendor_profile_name')
->find($id);
Then, your object will have a new attribute called "details" containing the related objects (or a collection of the limited selected fields).

You can convert the $vendor to an Array like below.
$vendor = Vendor::find($id)->toArray();

Related

Laravel relationship query where using array

I'm trying to return all the attributes from my database that have a set foreign key (Attribute groups). I've set up all the relationships in my model but I'm unsure how to query these relationships using a collection or array.
AttributeGroup -
public function attribute()
{
return $this->hasMany('App\Attribute', 'group_id');
}
Attribute -
public function attributeGroup()
{
return $this->belongsTo('App\AttributeGroup');
}
My current query -
$page = Page::where('slug', $slug)->firstOrFail();
$groups = AttributeGroup::where('page_id', $page->id)->get()->toArray();
$atts = Attribute::where('group_id', $groups[0]['id'])->get();
This works because we have set the specific index of the array using $groups[0]
Is there a simple way I can pass an array through to the query using their relationships or is looping through the results and then passing my own array to the query the best approach?
$attributes = array();
foreach ($groups as $group){
array_push($attributes, $group['id']);
}
$atts = Attribute::where('group_id', $attributes)->get();
$groups is a collection. Assume them as arrays on steroids. Therefore you can use the pluck() method to get those ids you need:
$page = Page::where('slug', $slug)->firstOrFail();
$groups = AttributeGroup::where('page_id', $page->id)->get();
$atts = Attribute::where('group_id', $groups->pluck('id'))->get();
Also if you've set your relationships correctly, you should be able to loop through $groups and access the attributes of those $groups. You can test it:
$groups = AttributeGroup::where('page_id', $page->id)->get();
dd($groups->first()->attributes);

Laravel - Carry array through map

Let's say I have a model collection that I'm mapping through like this:
$alreadyImported = [];
$players = Players::whereNotIn('id', $alreadyImported)
->get()
->random(25)
->pluck('id');
$groups = $players->map(function ($item, $key) use ($alreadyImported) {
array_merge($alreadyImported, $item->id);
$group = [
'username' => $item['username'],
];
return $group;
});
// $groups is a pivot table with group and players
Why does my $globalList always start at []? How can I carry the already-merged $globalList to the next map iteration?
The player IDs does not matter. It's for show. I am looking to pass the array through the map iterations.
Just use pluck() to get IDs from the collection:
$ids = $players->pluck('id');
Or, if you just need IDs:
$ids = Players::where('banned', false)->pluck('id');
If you're going to add any other data, you don't need to merge it to some array or a collection because map() will create a new collection.
Finally, you don't need to use collect() because get() will return collection.

How to create array with key => values from object{key, value}?

I solver this by this code
$service_list = Service::all();
$services = [];
foreach ($service_list as $item){
$services[$item['id']] = $item['name'];
}
but how to do that using php_array functions?
its for dropdown select
Not sure why you have to use PHPs built in array methods but we have pluck on the Query Builder and Collection class.
$services = Service::pluck('name', 'id');
// $services->all(); // for the actual array contained
This will only select the name and id in the query and give you a Collection keyed by the id only containing the name field.
$services = Service::all();
$services_array = $services->pluck('name', 'id')->all();
If you already have your collection of models (code above has queried for every field and hydrated models with the result) you can use pluck on the Collection to achieve the same result (though less efficient as it had to query for all fields, hydrate models, then pull those 2 fields from them)
Laravel 5.5 Docs - Query Builder - Retrieving Results
Laravel 5.5 Docs - Collections - pluck method
Use toArray() to convert the collection to an array, then use array_combine() to create an associative array from that.
$service_list = Service::all()->toArray();
$services = array_combine(array_column($service_list, 'id'), array_column($service_list, 'name'));
$service_list = Service::all()->toArray();
all() will return a collection. The collection supports a toArray() method

Return json with data from three tables in Laravel

//CartController
$itens = CartItem::where('id_cart', $cart->id)->with('product')->get();
return response()->json($itens);
This code returns a JSON with the data of the cart item and the relative product. But I also want to return the images of the product, which is in the ProductImages table.
In my model CartItem.php I have
public function product(){
return $this->belongsTo('App\Product', 'id_product');
}
In my model Product.php I have
public function images(){
return $this->hasMany('App\ProductImages', 'id_product');
}
But, if I do
$itens = CartItem::where('id_cart', $carrinho->id)->with('product')->with('image')->get();
I get the error
Call to undefined relationship [images] on model [App\CartItem]
You can try it as:
CartItem::where('id_cart', $carrinho->id)->with('product.images')->get();
To eager load nested relationships, you may use "dot" syntax.
Docs
You should load two tables by using with():
CartItem::where('id_cart', $cart->id)
->with('product', 'product.images')
->get();
You can read an explanation here (see Nested Eager Loading section).
you should make use of the nested eager load function:
$books = App\Book::with('author.contacts')->get();
https://laravel.com/docs/5.3/eloquent-relationships#eager-loading
Just use like this
$itens = CartItem::where('id_cart', $carrinho->id)->with('product','images')->get();

How to count and fetch data query in laravel?

How to merge this two queries ?
$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->count();
and
$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->get();
So, as far as I understand from your comment, you simply want to get all records from the table category_to_news and you want to know how many records are in there, right?
MySQL's count is an aggregate functions, which means: It takes a set of values, performs a calculation and returns a single value. If you put it into your names-query, you get the same value in each record. I'm not sure if that has anything to do with 'optimization'.
As already said, you simply run your query as usual:
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get(['title']);
$data is now of type Illuminate\Support\Collection which provides handy functions for collections, and one them is count() (not to be confused with the above mentioned aggregate function - you're back in PHP again, not MySQL).
So $data->count() gives you the number of items in the collection (which pretty much is an array on steroids) without even hitting the database.
Hi DB class dont return collection object it give error "call member function on array" but eloquent return collection object. for above code we can use collect helper function to make it collection instance then use count and other collection methods https://laravel.com/docs/5.1/collections#available-methods .
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get();
$data = collect($data);
$data->count();
You my get it using:
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get();
To get the count, try this:
$data->count();
Why you are using DB::table(...), instead you may use Eloquent model like this, create the model in your models directory:
class CategoryToNews extends Eloquent {
protected $table = 'category_to_news';
protected $primaryKey = 'id'; // if different than id then change it here
}
Now, you may easily use:
$data = CategoryToNews::whereName(ucwords($category))->get();
To get the count, use:
$data->count();

Categories