Expected type 'iterable|object'. Found 'string' - laravel

I am trying to iterate a set of array values returned from my laravel view in a multi-select dropdown field. When I submit my form, below is the data sent to my livewire component.
^ array:4 [▼
"scheduled_date" => "2022-09-30 12:00"
"recipient" => "2"
"classrooms" => array:4 [▼
0 => "2"
1 => "3"
2 => "4"
3 => "5"
]
"smsdetail" => "Testing for a particular Class"
]
I need to iterate data in classrooms array and save them as different records with the rest of the top-level data to db which is not the problem. My struggle is to iterate and pick values for classrooms.
The below set of codes gives me the error Expected type 'iterable|object'. Found 'string'. I need help.
case ('2'):
$recipients = $this->state['classrooms'];
foreach ($recipients as $key => $recipient)
{
dd($recipient);
}
case ('2'):
$recipients = $this->state['classrooms'];
foreach ($recipients as $recipient)
{
dd($recipient);
}

Related

Laravel : Countries with Laravel Analytics

I'm using Laravel Analytics to get data of the visitors of my application.
In my Google Analytics dashboard, every page have it own visits numbers, unique visitors, countries of visitors etc .. like in this image :
In my web.php, I'm creating a route to test the package :
Route::get('/data', function () {
$analyticsData = Analytics::fetchMostVisitedPages(Period::days(7));
dd($analyticsData);
});
This route returns :
Illuminate\Support\Collection {#1564 ▼
#items: array:3 [▼
0 => array:3 [▼
"url" => "/new"
"pageTitle" => "test"
"pageViews" => 1534
]
1 => array:3 [▼
"url" => "/"
"pageTitle" => "test"
"pageViews" => 450
]
2 => array:3 [▼
"url" => "/customize/8"
"pageTitle" => "test"
"pageViews" => 196
]
As you can see the returned array have only url, pageTitle and pageViews. How can I add additional informations in the returned array such as countries or geographic localisation as shown in the first image ?
I've never used the package, but reading the docs, something like this will do.
The package docs state you can use any query you want, and the Google Analytics docs give an example of getting session by location.
public function myCustomMethod($maxResults = 20)
{
$response = $this->performQuery(
$period,
'ga:sessions', // metrics
[
'dimensions' => 'ga:country',
'sort' => '-ga:sessions',
'max-results' => $maxResults,
],
);
return collect($response['rows'] ?? [])->map(fn (array $pageRow) => [
// Do something with the rows that are returned.
// I'm not sure how they're returned from the main response.
]);
}
Note, this is completely untested, you might want to fiddle with some of the data here.
Assuming I understand the documentation, this will get all countries (dimensions), it will use sessions (ga:sessions from second parameter) to measure the countries data.
It'll then just sort and get a maximum number of results.
You could change the metrics to ga:pageviews, but it's ultimately down to you what queries you want to use.
I've linked the documentation so you can find them out yourself.
You're using spatie/laravel-analytics package.
As you can see here: spatie laravel analytics - Analytics.php the fetchMostVisitedPages method that you are calling only returns that data.
Please take a look in github to see more information about this package.
fetchMostVisitedPages method:
public function fetchMostVisitedPages(Period $period, int $maxResults = 20): Collection
{
$response = $this->performQuery(
$period,
'ga:pageviews',
[
'dimensions' => 'ga:pagePath,ga:pageTitle',
'sort' => '-ga:pageviews',
'max-results' => $maxResults,
],
);
return collect($response['rows'] ?? [])->map(fn (array $pageRow) => [
'url' => $pageRow[0],
'pageTitle' => $pageRow[1],
'pageViews' => (int) $pageRow[2],
]);
}

Laravel Microsoft Graph request how to solve Cannot use object of type?

I try to do a graph request in my laravel project to connect Microsoft API. All works fine, but I don't find a way to get single data from my request.
$info = $graph->createRequest("GET", "/groups/{id}/calendar/events?\$filter=start/dateTime ge '" . $todayDate . "T00:00' and end/dateTime lt '" . $todayDate . "T23:00'")
->addHeaders(array("Content-Type" => "application/json"))
->setReturnType(\Microsoft\Graph\Model\User::class)
->setTimeout("1000")
->execute();
Output is a large json with all information. If I just want to get $info[0]['attendees'];
I get error: Cannot use object of type Microsoft\Graph\Model\User as array in file
Why? And how to access? If I try load object like $info->attendees I got error: Trying to get property 'attendees' of non-object.
This is my output (not all) of dd($info) it includes attendees as array like "id"
array:10 [▼
0 => Microsoft\Graph\Model\Event {#1532 ▼
#_propDict: array:43 [▼
"#odata.etag" => "{tag}""
"id" => "{id}"
"createdDateTime" => "2021-03-19T10:36:08.0812445Z"
"lastModifiedDateTime" => "2021-03-19T10:36:11.9402917Z"
"attendees" => array:1 [▼
0 => array:3 [▼
"type" => "required"
"status" => array:2 [▶]
"emailAddress" => array:2 [▼
"name" => "name"
"address" => "mail"
]
]
]
It seems your array is returning an array of attendees, you have an extra level in your array. So to fetch the first attendees status, you need to use the following code:
Try this
foreach($info as $item){
foreach($item as $inf ){
$a = $inf->status
dd($a)
}
}

Get all names from array and pluck them together Laravel 8

I got an array in witch are nested arrays and I want to get names from those nested arrays and display them together. I have been searching a lot and can't figure out how. I am using laravel 8.
array:2 [▼
"5dd48809b061f7a3828cb5267794ce39" => array:10 [▼
"name" => "test"
]
"7d504e7f837b2f9bb03dca5f9c8da9f5" => array:10 [▼
"name" => "test2"
]
]
You can do that in basic PHP with the array_column function.
$names = array_column($array, 'name');
The above example would output:
array(
[0] => 'test',
[1] => 'test2',
);
You can also keep the ID as key, if it exists within the nested array:
$names = array_column($array, 'name', 'id');
The above example would e.g. output:
array(
[1515] => 'test',
[2522] => 'test2',
);
There are more examples in the documentation:
https://www.php.net/manual/en/function.array-column.php

use sync method for an array and also add extra pivot fields?

This is my input array
"events" => array:2 [▼
"special-date" => array:3 [▼
0 => "14-Nov-1979"
1 => "18-Apr-1981"
2 => "12-Nov-1978"
]
"event" => array:3 [▼
0 => "2"
1 => "3"
2 => "4"
]
]
This is my code
$User->events()->sync($request->events['event'], ['event_date' => $request->events['special-date']]);
here, $user is an instance of the user model
This is my user model realtion function
public function events()
{
return $this->belongsToMany('App\Models\Event', 'user_events', 'user_id', 'event_id')->withPivot('event_date');
}
and I got an error of event_date has no default value.
my table structure of a user_event table is
id,
user_id,
event_id,
event_date

Convert an array of array onto Collection Laravel

I have an array of array which results from several sql requests.
First I make a sql request in a foreach in order to have all the datas i need
foreach ($users as $user) {
// Two different Eloquent requests
$todo = User::select().....where('users.id' = $id);
$done = User::select().....where('users.id' = $id);
// I have operation on Collection that work fine ...
$totalTimes = $todo->toBase()->sum('dureeformation') ;
$spendTimes = $done->toBase()->sum('dureeformation') ;
$remainingTimes = $totalTimes - $spendTimes;
$all[] = ['user_id' => $id, 'totalTime' => $totalTimes, 'spendTime' => $spendTimes,'remainingTime' => $remainingTimes ];
}
My issue is the following... Outside the foreach i display the values and i have this array of array ...
array:16 [▼
0 => array:4 [▼
"user_id" => 1
"totalTime" => 465
"spendTime" => 0
"remainingTime" => 465
]
1 => array:4 [▼
"user_id" => 3
"totalTime" => 375
"spendTime" => 0
"remainingTime" => 375
]
I would need to have a Collection instead ... I tried to make $all = Collect(....) but i doesn't give me the expected result.
I need a collection because i have to create a Collection with this created collection and another one from another request.
Concerning this part i already had this case and i can solve it.
Thanks for your help
try this helper function :
$collection = collect($all);
This function will convert your array to collection.

Resources