Exporting Excel getting this error Trying to get property 'id' of non-object - laravel

I'm using Maatwebsite Laravel Excel package 3.0.
This is my InvoicesExport.php
class InvoicesExport implements FromCollection
{
public function collection()
{
$company_id = Auth::user()->company_id;
$assets = Asset::where('id', $company_id)->get()->toArray();
$assets_array = array();
if(!$assets->isEmpty()){
foreach($assets as $asset){
$assets_array[] = array(
'Asset ID' => $asset->id,
'Asset Name' => $asset->name,
'Description' => $asset->description,
'Serial Number' => $asset->serialno,
'External ID' => $asset->external_id,
'Location' => $asset->location,
'Expiry Date' => $asset->expiry_date,
'Owner' => $asset->owner,
'Status' => $asset->status,
'Updated at' => $asset->updated_at
);
}
}
//dd($assets_array);
return $assets_array;
}
}
And i keep getting this error
Trying to get property 'id' of non-object
And this is my function in controller
public function excel()
{
return Excel::download(new InvoicesExport, 'invoices.xlsx');
}
My code looks like this now and I keep getting this error.
Call to a member function each() on array
When i use dd($assets_array) I get those 2 items that i have in database, so i think maybe it's problem in my RETURN

It seems, the problem is outside of the InvoicesExport Class.
Why don't you change the type of return?
instead of returning
return $assets_array;
Do it like this:
return collect($assets_array);

you convert the collection to array and try to access it as object
just remove the toArray
$assets = Asset::where('id', $company_id)->get();

Related

Laravel Livewire Dynamic Form Data Not Working

Quite new to Laravel Livewire. I'm trying to create a dynamic form for application but I couldn't quite understand how to attach additional data when storing.
The user selects the instructor(faculty_id), schoolyear(sy) and semester(sem). And new schedule and option to add more rows()
This is from my controller store() method
public function store()
{
$order = Emp_sched::create([
'faculty_id'=>$this->faculty_id,
'sem'=>$this->sem,
'sy'=>$this->sy,
]);
foreach ($this->createScheds as $sched) {
$order=(['corsdes' => $sched['corsdes']],
['c_time' => $sched['c_time']], ['day' => $sched['day']], ['room' => $sched['room']]);
}
return 'Schedules Saved!';
}
You must call Model::create inside loop
public function store()
{
foreach ($this->createScheds as $sched) {
$createArray = array_merge([
'faculty_id' => $this->faculty_id,
'sem' => $this->sem,
'sy' => $this->sy,
],[
'corsdes' => $sched['corsdes'],
'c_time' => $sched['c_time'],
'day' => $sched['day'],
'room' => $sched['room'],
]);
Emp_sched::create($createArray);
}
return 'Schedules Saved!';
}

Convert API resource to array

I want to store data on Firestore. I need to send an array to Firestore. I have API resources and I wanted to use it.
My ApiResource:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'phone' => $this->phone,
'addresses' => AddressResource::collection($this->addresses),
];
}
Firestore store data:
public function set(User $user){
$this->firestore->document($user->id)->set((new UserResource($user)));
}
It is an error:
Argument 1 passed to
Google\Cloud\Firestore\DocumentReference::set() must be of the type
array, object given,...
You can call the toJson() on your Api Resource object:
$data = MyModel::with('addresses')->find(1);
$myArray = json_decode((new MyModelResource($data))->toJson(), true);
So you could just:
$this->firestore->document($user->id)->set($myArray);
Do it:
public function set(User $user){
$this->firestore->document($user->id)->set(toArray($user));
}

When collection->map returnes array then data in Collection raise error

In laravel 6 app I have collection defined as :
class PermissionCollection extends ResourceCollection
{
public static $wrap = 'permissions';
public function toArray($request)
{
return $this->collection->transform(function($permission){
return [
'id' => $permission->id,
'name' => $permission->name,
'is_checked' => !empty($permission->is_checked) ? $permission->is_checked : null,
'guard_name' => $permission->guard_name,
'created_at' => $permission->created_at,
];
});
}
}
I use it in a control, like :
$permissions = $user->permissions->all();
$userPermissionLabels= Permission
::get()
->map(function ($item) use($permissions) {
$is_checked= false;
foreach( $permissions as $nextPermission ) {
if($nextPermission->permission_id === $item->id) {
$is_checked= true;
break;
}
}
return [ 'id'=> $item->id, 'name'=> $item->name, 'is_checked' => $is_checked];
})
->all();
return (new PermissionCollection($userPermissionLabels));
and I got error :
Trying to get property 'id' of non-object
Looks like the reason is that collection->map returnes array of data, not objects.
If there is a way to fix it without creating new collection(using array) ?
MODIFIED :
I logged loging in my collection,
public function toArray($request)
{
return $this->collection->transform(function($permission){
\Log::info(' PermissionCollection $permission');
\Log::info($permission);
return [
'id' => $permission->id,
'name' => $permission->name,
'is_checked' => !empty($permission->is_checked) ? $permission->is_checked : null,
'guard_name' => $permission->guard_name,
'created_at' => $permission->created_at,
];
});
}
and I see in logs:
PermissionCollection $permission
array (
'id' => 1,
'name' => 'App admin',
'is_checked' => false,
)
local.ERROR: Trying to get property 'id' of non-object
The value is valid array, not null.
I mean I have already use this collenction in other part of the app, can I use it without creating a new one...
I think you get this error because you CollectionResource need to object of the Permission model, but in your case it is trying to get id from an array, after map function. Try to extend your model instead of returning an new array

Laravel putting the return of a trait array into the controller

I'm currently struggling with how to return a variables from a trait and it should be returned in the array to be used in the controller:
Trait:
public function getAllData($search)
{
if ($search->search == null) {
$search->search = '#technology';
}
$cb = new Codebird();
$cb->setConsumerKey(env('TwitterKey'), env('TwitterSecret'));
$cb->setToken(env('AccessToken'), env('AccessTokenSecret'));
//https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
//https://dev.twitter.com/docs/api/1.1/get/search/tweets
$params = [
'q' => $search->search,
'lang' => 'en',
'count' => '5',
];
$reply = (array)$cb->search_tweets($params);
$data = (array)$reply['statuses'];
$s = count($reply['statuses']);
return [
'data' => $data,
's' => $s,
];
Controller:
public function TwitterData(Request $search) {
$data = $this->getAllData($search);
return view('front.search', compact('data'));
}
It currently gives me an error saying about using the object however I can't access the 'data' in the array
Error:
Trying to get property of non-object (View: C:\xampp\htdocs\TwitterProject\resources\views\front\search.blade.php)
You are returning an array on your getAllData method, but you are probably trying to access it as an object on your View:
WRONG:
{!! $data->data !!}
RIGHT:
{!! $data['data'] !!}

Laravel 4.2: Can't Use Transformer with DB::Raw Query

Throughout my app, I have been taking the results of an Eloquent query and channeling it through a transformer and it is working well. This is what I am doing:
public function index()
{
$users = User::with('profile', 'location', 'role')->get();
return $this->respond([
'data' => $this->userTransformer->transformCollection($users->all())
]);
}
However, I ran into a situation where to produce a nested resource I needed to use a DB::RAW query
public function byLoan($id)
{
$users = DB::select( DB::raw("SELECT * FROM users WHERE id IN (SELECT DISTINCT(user_id) FROM farms WHERE user_id = {$id})") );
return $this->respond([
'data' => $this->userTransformer->transformCollection($users->all())
]);
}
The code above gave me this error "Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR) Call to a member function all() on array".
I changed transformCollection($users->all()) to transformCollection($users) and now the error is this "Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR) Cannot use object of type stdClass as array".
I don't know what else to try.
My Transformer class looks like this:
<?php namespace Acme\Transformers;
abstract class Transformer {
public function transformCollection(array $items)
{
return array_map([$this, 'transform'], $items);
}
public abstract function transform($item);
}
And the UserTransformer implentation:
<?php namespace Acme\Transformers;
class UserTransformer extends Transformer
{
public function transform($arr)
{
//return $arr;
return [
'id' => $arr['id'],
'username' => $arr['username'],
'abr' => $arr['abr'],
'email' => $arr['email'],
'phone' => $arr['phone'],
'role_id' => $arr['role_id'],
'role_abr' => $arr['role']['abr'],
'role' => $arr['role']['role'],
'loc_id' => $arr['location']['id'],
'loc_abr' => $arr['location']['loc_abr'],
'region_id' => $arr['location']['region_id'],
'is_admin' => (boolean) $arr['is_admin'],
'is_manager' => (boolean) $arr['is_manager'],
'show_agency' => (boolean)$arr['profile']['show_agency'],
'show_balance_due' => (boolean)$arr['profile']['show_balance_due'],
'show_close_date' => (boolean)$arr['profile']['show_close_date'],
'show_commit_arm' => (boolean)$arr['profile']['show_commit_arm'],
'show_region' => (boolean)$arr['profile']['show_region'],
'show_season' => (boolean)$arr['profile']['show_season']
];
}
}
First off, don't use all() on a DB::select. The select method does execute the query as soon as it's called. Also all() is for Eloquent models only.
However the bigger problem here, is how a Query Builder result is structured. Its an array (of all rows) filled with objects (the individual row, with properties for each column)
So that means, passing it to your transform method and then accessing the columns like an associative array doesn't work. Example:
$arr['id']
What you would have to do instead is:
$arr->id // obviously the name $arr doesn't make any sense now because its an object..
If this messes up the other usages of transform() you should also be fine by just adding
$arr = (array) $arr;
at the beginning of the function. This converts the object into an array and makes sure you can access it like $arr['id']

Resources