Laravel putting the return of a trait array into the controller - laravel

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'] !!}

Related

Laravel : array_push not working in collection->each() iterator

I have grouped collection and I iterate it using each() function.Inside the each function I want to add element to some array.But it is not working.Any idea?
$dataSet1 = [];
$appointments = [
['department' => 'finance', 'product' => 'Chair'],
['department' => 'marketing', 'product' => 'Bookcase'],
['department' => 'finance', 'product' => 'Desk'],
];
$groupData = collect($appointments)->groupBy('department');
$groupData->each(function ($item, $key) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Laravel version : 8.35.1
You need to pass the array to the function with use:
$groupData->each(function ($item, $key) use (&$dataSet1) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Pass-by-reference (&) is needed as long as $dataSet1 is not an object instance.

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

How to define variable in controller in laravel

I have a URL used in blade template as:
href="{{ route('download', ['year' => $year, 'month' => $month, 'file' => $file_path]) }}"
when I am running my code then it is giving me an error as:
Undefined variable: year (View: C:\wamp64\www\Blog\employee-portal\resources\views\finance\invoice\edit.blade.php)
How can i define this $year variable in my controller?
In my controller the function is written as:
public function download($year, $month, $file, $inline = true)
{
$headers = [
'content-type' => 'application/pdf',
];
$file_path = FileHelper::getFilePath($year, $month, $file);
if (!$file_path) {
return false;
}
if ($inline) {
return Response::make(Storage::get($file_path), 200, $headers);
}
return Storage::download($file_path);
}
}
Edit function is written as:
public function edit(Invoice $invoice)
{
$projectStageBillings = $invoice->projectStageBillings;
$projectStageBilling = $projectStageBillings->first();
$client = $projectStageBilling->projectStage->project->client;
$client->load('projects', 'projects.stages', 'projects.stages.billings');
$billings = [];
foreach ($projectStageBillings as $key => $billing) {
$billing->load('projectStage', 'projectStage.project');
$billings[] = $billing;
}
return view('finance.invoice.edit')->with([
'invoice' => $invoice,
'clients' => Client::select('id', 'name')->get(),
'invoice_client' => $client,
'invoice_billings' => $billings,
]);
}
This error states that the view finance\invoice\edit.blade.php is missing the variable $year. And it is true, take a look at the return of your edit function:
return view('finance.invoice.edit')->with([
'invoice' => $invoice,
'clients' => Client::select('id', 'name')->get(),
'invoice_client' => $client,
'invoice_billings' => $billings,
]);
You are not sending any $year variable to the view here (the variables sent to the view are invoice,clients,invoice_client and invoice_billings.
To solve your problem, just send a $year variable to the view and you'll be ok :)

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

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();

Difference between Redirect::to() and View::make()

I have a blade form that posts to Controller, the controller then will redirect to the same URL after performing some operations.
Before redirecting to the user, two variables will be passed. My problem is that when using Redirect::to() only the ->with('item_list',$item_list) is made available for the view, while ->with('added_items',$added_items) when using the $added_items variable in the view gives me the error:
ErrorException
Undefined variable: added_items (View: /var/www/mw/app/views/delivery->
requests/create.blade.php)
Controller
if (Input::has('addItem'))
{
if (Session::has('added-items'))
{
$id = Input::get('item_id');
$new_item = Item::find($id);
Session::push('added-items', [
'item_id' => $id,
'item_name' => $new_item->item_name,
'item_quantity' => Input::get('item_quantity')
]);
$array = Session::get('added-items');
//move outside foreach loop because we don't want to reset it
$total = array();
foreach ($array as $key => $value)
{
$id = $value['item_id'];
$quantity = $value['item_quantity'];
if (!isset($total[$id]))
{
$total[$id] = 0;
}
$total[$id] += $quantity;
}
$items = array();
foreach($total as $item_id => $item_quantity)
{
$new_item = Item::find($item_id);
$items[] = array(
'item_id' => $item_id,
'item_name' => $new_item->item_name,
'item_quantity' => $item_quantity
);
}
Session::put('added-items', $items);
}
else
{
$id = Input::get('item_id');
$new_item = Item::find($id);
Session::put('added-items', [
0 => [
'item_id' => $id,
'item_name' => $new_item->item_name,
'item_quantity' => Input::get('item_quantity')
]
]);
}
// pass the items again to the page
$item_list = Item::lists('item_name', 'id');
$added_items = Session::get('added-items');
return View::make('delivery-requests/create')
->with('added_items',$added_items)
->with('item_list', $item_list);
}
The reason I used Redirect::to() is that it maintains the same URL which is /delivery-requests/create
But when I use View::make() I can access the $added_items variable just fine, but the URL now becomes /delivery-requests , even if I explicitly put it like this:
return View::make('delivery-requests/create')
->with('added_items',$added_items)
->with('item_list', $item_list);
My question is why can't Redirect::to() read the $added_items variable on the view
Instead of redirecting to the route, return the method which is at the end of that route with any additional variables you need.
return $this->create()->with('added_items', $added_items)->with('item_list', $item_list) where create() is the method which is being used on the route delivery-requests/create.
Redirect is probably what you are actually after then,
Redirect::to()->with('item_list', $item_list);

Resources