I'm trying to export a query result in Laravel 5 to Excel, but I'm getting the error
Object of class stdClass could not be converted to string
when I use the code below:
$equipements=Equipement::all();
$equipements=collect($equipements)->toArray();
Excel::create('Inventaire',function($excel) use ($equipements){
$excel->sheet('Page 1',function ($sheet) use($equipements){
$sheet->fromArray($equipements);
});
})->export('xlsx');
But that's not the result I want, I want to specify columns from different tables. Is there any way to convert a collection to array of strings the method collection->torray return array of objects that's not what I want.
When sending $equipements to the fromArray() method, you're passing an array to that method. But you're sending the array of all equipements and each single equipement is an instance of the Equipement model.
To send each equipements to it's own row, use the following code:
Excel::create('Inventaire', function($excel) {
$excel->sheet('Page 1', function ($sheet) {
$equipements = Equipement::all();
foreach ($equipements as $equipement) {
$sheet->fromArray($equipement);
}
});
})->export('xlsx');
One thing to notice is that the all() method of a model already returns a Collection so no need to collect() that data again.
Related
Here is a table with two fields: startitime, endtime. I pull out data using:
ScheduleModel::all();
It returns me a data collection.
How to get result in plain array like this: [starttime1, endtime1, starttime1, endtime2...]
I have tried to use pluck() but it returns me an array with (key => value) instead plain array.
Try this:
$scheduleVal = ScheduleModel::all();
$scheduleTime = array();
foreach ($scheduleVal as $schedule) {
array_push($scheduleTime, $schedule->starttime, $schedule->endtime);
}
dd($scheduleTime);
What im trying to do is to make this join into a scope function
$workorders =\DB::table('users')->leftjoin('work_orders','users.id','=','work_orders.user_id')->select('users.id','users.name','users.email','users.status','work_orders.cod','work_orders.deadline'->where('users.id','=','1');
$workorders = $workorders->get();
This is what I've tried with no success...
public function scopeOrders($query){
return $query->join('work_orders','users.id','=','work_orders.user_id')
->select('users.id','users.name','users.email','users.status','work_orders.cod','work_orders.deadline')
->where('users.id','=','1');
}
Expected result using the scope in a query
$usersWO = User::Orders()->get();
The only difference between $workorders = $workorders->get(); and $usersWO = User::Orders()->get(); is the output format. They both are bug-free.
A dd() on the former outputs a collection of stdClass objects with record values as properties.:
A dd() on the latter outputs a collection of models:
To modify the output of the second to look exactly like the first, you'll have to modify the client code since scopes return collections of models.
$usersWO = User::Orders()->get()->map(function ($user) {
return (object) $user->getAttributes();
});
I have a Accessor method in Collection Model getSizesAttribute, which returns array of available sizes eg: ['S','L'], Now I need to get Models with have size 'S'. like:
$collections = $collections->where('sizes','S');
But sizes is array, could I manipulate this anyhow so that I could check returns only if sizes have specific size.
I tried making another method getIsSizeAttribute, like:
public function getIsSizeAttribute($size){
return in_array($size,$this->sizes);
}
Now How could I user this in Where condition like
$collections = $collections->where('is_size','S');
Mutators and Accessors only run skin-deep, after the query's already been executed. You could use Collection::filter() as Bangnokia suggests, but that wouldn't give you any performance benefit of actually applying the condition to the initial request.
I think what you're looking for here is a Query Scope. Add something like this to your Model class:
public function scopeSize(\Illuminate\Database\Eloquent\Builder $query, $size)
{
return $query->whereIn('sizes', $this->sizes[$size]);
}
And access it like this:
$collection = $model->size('S')->get();
You should use filter on collection
$collections = $collections->filter(function($item, $index) {
return in_array('S', $item->sizes);
});
I have a table 'tour2s' with 2 rows and when I do:
$tour = Tour2::find(1);
dd($tour);
it returns the tour with 'id' = 1. And it's Object.
I want to turn the object to collection of only attributes of the model, nothing else. And I know that when I use ->get() it returns collection.
But when I am trying:
$tour = Tour2::find(1)->get();
dd($tour);
It returns a collection but of all 2 tour objects (full objects, not only attributes):
I did it like:
$tour = Tour2::find(1);
$tour = collect($tour);
dd($tour);
and now it's what i what - it return a collection of only model attributes (WHAT I WANTED):
SO, my question is why when I used $tour=Tour2::find(1)->get() it returned all tours not only the one with 'id'=1 ?
Passing an array to find() will return a collection.
$tour = Tour2::find([1]);
However, it will be a collection of Tour2 objects, not only the attributes.
Then, if you want only the attributes, you could use $tour->toArray()
You could also do $tour = collect(Tour2::find(1));
And to answer your question, when you use $tour=Tour2::find(1)->get(), Laravel fetch the first tour, and then calling get() on $tour will fetch all other records, so return two tours in your case.
Ok, the main question, as i understand is: "Why when i wrote Tour2::find(1)->get() i receives collection of all records".
when you wrote Tour2::find(1) it assumes that you receive instanse of model Tour2. So we can simple write $tourInstanse->get()
If you go to \Illuminate\Database\Eloquent\Model you can see that here is no method called get() but we have a magic method __call. Look at his implementation:
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
return $this->newQuery()->$method(...$parameters);
}
So, when you call get() method on a model instance you get model`s QueryBuilder (as described in last row) and call get() method on a QueryBuilder. As a result, you receiving all records of that model Class.
I'm trying to get my route to insert a new row into the database, and if successful return the record (with its new primary key id) in some JSON. I'm getting the following error:
{
"error":
{
"type":"BadMethodCallException",
"message":"Call to undefined method Illuminate\\Database\\Query\\Builder::to_array()",
"file":"\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php",
"line":1418
}
}
This is my route:
Route::post('/client/create', function()
{
$client = Client::create(Input::all());
if($client)
{
return json_encode(array('Result' => 'OK', 'Record' => $client->to_array()));
}
else
{
return json_encode(array('Result' => 'ERROR', 'Message' => 'Error Inserting Record =('));
}
});
According to the Laravel docs I've read, you're supposed to use ->to_array() to convert your model to an array, and ::create returns an instance of the model if successfully inserted. I've checked the database, and the records are being inserted just fine.
By default if you were to return an Eloquent model directly it would convert the model to it's JSON representation. This is because the __toString magic method on each model returns the model as JSON by using the toJson method.
As such the model implements both the ArrayableInterface and JsonableInterface. That means you can directly call toJson or toArray on a model.
Now you can mark columns as hidden. This means that when a model is converted into it's array or JSON representation some columns are removed (think publicly accessible API, you don't want passwords showing up!). I'm not totally sure but maybe the ID of your model is being hidden.
At the end of the day, all you need to do is return the instance.
return $client;
It'll be converted to JSON for you automatically.
The to_array() method comes from Laravel 3. Use toArray() in Laravel 4.
I see question similar you try to return data to jquery jtable and same me
Player::orderBy($sort)->paginate($pagesize)->getCollection();
return Response::view(array('Result'=>'OK','Records'=>$player->toArray()));
for try many hour I found solution getcollection pull instance from object and then solve