Replicating models across 2 systems - laravel

I have 2 systems which are seperate from each other. To let them communicate I have built an API. Both systems have common Models, one of which is a Project Model with all its relationships.
Within System A, to send a Project with its relationships I do the following.
$client = new GuzzleHttp\Client();
$jsonProject = json_encode(Project::with('projectType', 'projectType.projectTypeData',
'projectAssets', 'projectAssets.projectAssetsData')->find($project->id));
$req = $client->request('POST', 'https://someurl/postProject', [
'body' => json_encode($jsonProject),
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($jsonProject),
]
]);
Within System B I have the routes set up, and when the above is posted the following is triggered
public function store(Request $request)
{
$project = $request->all();
dd($project);
}
When I make the post request from System A I see something like this because of the dump in System B (I have removed a lot of the output to cut down on code).
array:17 [
"id" => 3
"projectName" => "Test Project"
"user_id" => 1
"contact" => "John Doe"
"project_type" => array:7 [
"id" => 3
"project_id" => 3
"project_type_data" => array:1 [
0 => array:8 [
"id" => 5
"projectType" => "Standard"
]
]
]
"project_assets" => array:7 [
"id" => 2
"project_id" => 3
"project_assets_data" => array:4 [
0 => array:8 [
"id" => 5
"label" => "Logo"
"altTag" => ""
"urlPath" => ""
"projectAssetsId" => 2
]
]
]
]
So everything seems to work fine. My question is this. System B now has a load of json data containing all the data required to make the models. If I was able to send a model via the api (not json) then I could easily create the model within System B. Because it is json data however, and I cant decode it because it is not a string, do I have to start looping it all in order to make my models?

Related

Laravel Excel Row Validation with conditions depends on another field input

I need to validate every rows from excel user upload in laravel which already converted to numeric array.
The validation i wanted is :
to make sure that the 1st field (0) is not blank,
then check whether the input is 'PRODUCTION-PROJECT' or not, if yes, then the 2nd field is required (1).
how to achieve this ?
My Controller Import class
$file = $request->file('file');
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setLoadSheetsOnly(['Upload']);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file->getRealPath());
$sheet = $spreadsheet->getActiveSheet();
$array = $sheet->toArray();
The array looks like this :
array:8 [
0 => array:11 [
0 => "PRODUCTION-PROJECT"
1 => "Consumable equipment expenses"
2 => "2022-07"
3 => "2022-08"
4 => "Forstr"
5 => "DOMESTIC"
6 => "ABCDE"
7 => "IDR"
8 => 2000
9 => 1
10 => "Enim temporibus est quis."
],
1 => array:11 [
0 => "PRODUCTION-PROJECT"
1 => null
2 => "2022-08"
3 => "2022-08"
4 => "RX"
5 => "DOMESTIC"
6 => "FGHIJ"
7 => "USD"
8 => 2000
9 => 1
10 => null
],
];
The validation i've tried so far like so :
$validatedData = Validator::make($array, [
'*.0' => 'required',
'*.1' => Rule::requiredIf('*.0' === 'PRODUCTION-PROJECT')
];
and the validation didn't show any error
The params of Rule::requiredIf should be a callback function that you need to custom the rule and input.
It's better to change Rule::requiredIf('*.0' === 'PRODUCTION-PROJECT') to 'required_if:*.0,PRODUCTION-PROJECT"'
so the correct code is :
$validatedData = Validator::make($array, [
'*.0' => 'required',
'*.1' => 'required_if:*.0,PRODUCTION-PROJECT'
];

Custom conditional validation laravel

I have a request data like this.
array:6 [
"teacherid" => "1"
"classid" => "7"
"schedule" => array:5 [
0 => "Monday - lesson 1"
1 => "Monday - lesson 2"
2 => "Monday - lesson 3"
3 => "Wednesday - lesson 3"
4 => "Wednesday - lesson 4"
]
"year" => "2021"
"smt" => "1"
"_token" => "tSFppSS2TWPQYbQofJD6pPufTLFNpKWAssZNGIHO"
]
and DB look like this
table schedules
I want to validate the input teacher, schedule and classroom like this:
if schedule, teacher and classroom are duplicate
or if schedule and teacher duplicate, but different classroom
I've tried with rule::unique as below but validation doesn't work.
how to make validation of point 1 and 2 above with rule::unique ?
$messages = ['schedule.*.unique' => 'Schedule :input already taken'];
$validator = \Validator::make(
$request->all(),
[
'schedule.*' => 'required',
Rule::unique('schedules')->where(function ($query) use ($request) {
return $query->where('schedule', $request->schedule);
->where('teacher_classes_id', $request->classid)
->where('teacher_subjects_id', $request->teasubid);
}),
],
$messages
);

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],
]);
}

select data based on the array

I have an array from query like below:
array:84 [
0 => array:2 [
"comp" => "50007148"
"cus" => "F0401"
]
1 => array:2 [
"comp" => "50007148"
"cus" => "J0050"
]
2 => array:2 [
"comp" => "50007148"
"cus" => "L"
]
3 => array:2 [
"comp" => "50007148"
"cus" => "LT"
]
4 => array:2 [
"comp" => "50007148"
"cus" => "RP"
]
Now I need to write a query where comp, cus in above query.
$rslt = Stdetl::whereIn('comp, cus', $categories)
->where(YEAR(docdate), '=', 2019)
->get(SUM(number))->toArray();
But this query is not working. I am getting error as follows:
(1/1) FatalErrorException
Call to undefined function App\Http\Controllers\YEAR()
But this is not the only mistake in that query .
YEAR() is a mysql function, you should use whereRaw() to query this. Like this:
->whereRaw('YEAR(docdate) = 2019')
Update:
For your whereIn() part, you have to make two queries, one for each column. So you will have to get the correct values from the array. This can be done using array_map.
For example:
->whereIn('comp', array_map(function($cat) { return $cat['comp']; }, $categories))
->whereIn('cus', array_map(function($cat) { return $cat['cus']; }, $categories))
You can't use whereIn like that, use this way
$rslt=Stdetl::whereIn('comp', $categories)
->whereIn('cus', $categories)
->where(date('Y', strtotime(docdate)), '=', 2019)
->get(SUM(number))->toArray();;

Facebook marketing API insights (Destination url)

I'm trying to get data using Facebook Marketing API.
$api = FacebookAds::init('TOKEN');
$start = Carbon::create(2018,11,16);
$end = Carbon::create(2018,11,16);
$period = Period::create($start,$end);
$in = $api->insights($period,'act_ID', 'ad',[
'fields' => ['impressions', 'objective', 'actions'....]
]);
I'm getting each ad actions like this:
"actions" => array:10 [▼
0 => array:2 [▼
"action_type" => "comment"
"value" => "1"
]
1 => array:2 [▼
"action_type" => "offsite_conversion.fb_pixel_purchase"
"value" => "1"
]
2 => array:2 [▼
"action_type" => "photo_view"
"value" => "114"
]....
]
My question is how to get each ad destination URL?
Thanks
You actually have to use AdCreative information to get the destination URL: https://developers.facebook.com/docs/marketing-api/reference/ad-creative/
I use the object_story_spec and match the AdCreative with the Ad by id ( they share the same ID ).
https://graph.facebook.com/v14.0/'adcreativeid'/?fields=object_story_spec
You can use this code. Destination URL will mentioned in link data -> link

Resources