How to properly fix - Cannot use empty array elements in arrays - php

I have the code below but it showing an error "Cannot use empty array elements in arrays".
It seems that the issue is in this line }), collect(json_decode($post['comments'], true))->map(function ($comment) {
Code:
'data' => [
'comments' =>
collect(json_decode($configs['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}), collect(json_decode($posts['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]

If we simplify your code it seems like this;
'data' => [
'comments' =>
collect(),
collect()
]
It is not a valid syntax. You can try like this;
$comments = collect(json_decode($configs['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
});
$postComments = collect(json_decode($posts['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
});
'data' => [
'comments' => $comments->merge($postComments)->toArray()
];

Related

how to render columns in laravel datatable?

i'm got stuck for 2 days, i got confused how to render column usind yajra/laravel-datatable
i'm using postgre as database, and yajra/laravel-datatables as package.
i have query builder like this
$data = DB::select("SELECT * FROM get_list_count_amount_transaction('chat', 'done', '2019-03-01', '2021-12-31' )")[0];
which generates a value of object : (i use var_dump() to see the value)
{ ["list_data"]=> string(2171)
"[{"id":"44649ccd-9195-4964-b48c-ed2098077dc5","kd_join":1,"status":"done","booking_date":"2021-04-18","transaction_type":"chat","price":4000.00,"date_create":"2021-04-18T19:56:57"},
{"id":"e500d2c1-99ae-4436-8ecc-8073f4f05bba","kd_join":1,"status":"done","booking_date":"2021-03-20","transaction_type":"chat","price":10000.00,"date_create":"2021-03-19T21:41:41"}
]"
["count_transaction"]=> int(12)
["total_amount_transaction"]=> string(9) "160500.00"
}
i'm confused, how to render list_data into a table using datatble
this is my html builder function :
public function html()
{
return $this->builder()
->columns($this->getColumns())
->minifiedAjax()
->addAction(['width' => '200px'])
->addColumnBefore([
'defaultContent' => '',
'data' => 'DT_Row_Index',
'name' => 'DT_Row_Index',
'title' => 'No',
'render' => function () {
return 'function(data,type,fullData,meta){return meta.settings._iDisplayStart+meta.row+1;}';
},
'orderable' => false,
'searchable' => false,
'exportable' => false,
'printable' => true,
'footer' => '',
]);
}
protected function getColumns()
{
return [
['data' => 'transaction_type', 'name' => 'transaction_type', 'title' => 'Tipe Transaksi', 'orderable' => false],
['data' => 'status', 'name' => 'status', 'title' => 'Status', 'orderable' => false],
['data' => 'booking_date', 'name' => 'booking_date', 'title' => 'Tanggal Booking', 'orderable' => false],
['data' => 'price', 'name' => 'price', 'title' => 'Jumlah', 'orderable' => false],
];
}
}
Just grab the list_data, use json_decode and laravel collection to make your needed structure. Try to use map, filter, mapWithKeys or whatever suitable.
For Instance:
collect(json_decode($listData))->mapWithKeys(function($item)){
//
}

Refactor array of function values

I have the following code that contains too much duplication, and I want to simplify it. I am not a back-end dev and have rudimentary php skills, so I will appreciate any help:
'gateways' => [
'cod' => [
'initializePayment' => function(OrderPage $virtualOrderPage): OrderPage {
return $virtualOrderPage;
},
'completePayment' => function(OrderPage $virtualOrderPage, array $data): OrderPage {
$virtualOrderPage->content()->update([
'paymentComplete' => true,
'payedDate' => date('c'),
]);
return $virtualOrderPage;
}
],
'deposit' => [
'initializePayment' => function(OrderPage $virtualOrderPage): OrderPage {
return $virtualOrderPage;
},
'completePayment' => function(OrderPage $virtualOrderPage, array $data): OrderPage {
$virtualOrderPage->content()->update([
'paymentComplete' => true,
'payedDate' => date('c'),
]);
return $virtualOrderPage;
}
],
],
Just pulling the arrayFunc out would clear code a bit
$arrayFunc = [
'initializePayment' => function(OrderPage $virtualOrderPage): OrderPage {
return $virtualOrderPage;
},
'completePayment' => function(OrderPage $virtualOrderPage, array $data): OrderPage {
$virtualOrderPage->content()->update([
'paymentComplete' => true,
'payedDate' => date('c'),
]);
return $virtualOrderPage;
}
];
'gateways' => [
'cod' => $arrayFunc,
'deposit' => $arrayFunc,

How to solve this error: explode() expects parameter 2 to be string, object given?

I'm trying to setup different user types and their respective permissions in my AppServiceProvider.php in my project, and I get the error
explode() expects parameter 2 to be string, object given
Nowhere in my code do I have an explode() at least that I can see. Before adding the Inertia::share(function(){}) there was no such error.
This is my code:
public function register()
{
Inertia::version(function () {
return md5_file(public_path('mix-manifest.json'));
});
Inertia::share(function () {
$auth = null;
if (Auth::user()) {
$perms = [];
$user = Auth::user();
if ($user->isSuperAdmin() || $user->isAdmin()) {
$perms = [
[
'url' => '/',
'icon' => 'fa fa-home',
'name' => 'Dashboard'
],
[
//rest of permissions
],
];
}
if ($user->isUser()) {
$perms = [
[
'url' => '/',
'icon' => 'fa fa-home',
'name' => 'Dashboard'
],
[
//rest of permissions
],
];
}
$auth = [
'id' => Auth::user()->id,
'name' => Auth::user()->name,
'card' => Auth::user()->card,
'scard' => Auth::user()->scard,
'user_type_id' => Auth::user()->user_type_id,
'email' => Auth::user()->email,
'perms' => $perms
];
}
return [
'app' => [
'name' => Config::get('app.name'),
],
'auth' => [
'user' => $auth,
],
'flash' => [
'success' => Session::get('success'),
],
'errors' => Session::get('errors') ? Session::get('errors')->getBag('default')->getMessages() : (object)[],
]
});
What am I doing wrong? Where i'm getting the error it doesn't specify where the error is, just what it is, it signals the last line of the code I presented as where the error is, but all that's there is the closing parenthesis and brackets.
Knowing nothing of Inertia, it seems you are misusing the Inertia::share function. In their docs, I see 3 examples. The first two have parameter 1 being a string (eg. 'auth.user' or 'app.name'), and the last has parameter 1 being an associative array, so each element still has a unique string key.
In your code, you are passing a closure as the first parameter. I believe that you can fix it by simply adding a name as the first parameter:
Inertia::share('auth.user', function () {
$auth = null;
if (Auth::user()) {
$perms = [];
$user = Auth::user();
if ($user->isSuperAdmin() || $user->isAdmin()) {
$perms = [
[
'url' => '/',
'icon' => 'fa fa-home',
'name' => 'Dashboard'
],
[
//rest of permissions
],
];
}
if ($user->isUser()) {
$perms = [
[
'url' => '/',
'icon' => 'fa fa-home',
'name' => 'Dashboard'
],
[
//rest of permissions
],
];
}
$auth = [
'id' => Auth::user()->id,
'name' => Auth::user()->name,
'card' => Auth::user()->card,
'scard' => Auth::user()->scard,
'user_type_id' => Auth::user()->user_type_id,
'email' => Auth::user()->email,
'perms' => $perms
];
}
return [
'app' => [
'name' => Config::get('app.name'),
],
'auth' => [
'user' => $auth,
],
'flash' => [
'success' => Session::get('success'),
],
'errors' => Session::get('errors') ? Session::get('errors')->getBag('default')->getMessages() : (object)[],
];
});

Callback Validator not firing?

Whenever I submit the form I'm expecting for die() to get fired the Callback Validator doesn't seem to get triggered?
I can't figure out what else I'm missing as I just based this on several examples I saw online.
$inputFilter->add([
'name' => 'flag_reference',
'required' => true,
'allow_empty' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class]
],
'validators' => [
[
'name' => Callback::class,
'options' => [
'messages' => [
Callback::INVALID_VALUE => 'Not a valid Reference'
],
'callback' => function($value, $context) {
die('here');
$flagReference= $value;
var_dump('flag reference', $value);
$flag = $context['flag'];
var_dump('flag', $canonicalFlag);exit;
$isValid = false;
if($flag== 'checked') {
$isValid = $flagReference ? true : false;
}
return $isValid;
}
],
]
]
]);
I'm expecting the response to be 'here' but I just get validation errors for the other elements.
Basically I'm trying to accomplish a conditional required.
If a checkbox is checked (flag), the value for a textbox must not be empty (flag_reference).

How to filter in nested collections?

Hello StackOverflow community, I am working with laravel and i created this collection
$headquarters = collect([
[
'headquarter' => 'Leon',
'offers' => [
[
'name' => 'Name1',
'slug' => 'Name1'
], [
'name' => 'Name2',
'slug' => 'Name2'
]
]
],[
'headquarter' => 'Granada',
'offers' => [
[
'name' => 'Name3',
'slug' => 'Name3'
],[
'name' => 'Name4',
'slug' => 'Name4'
],[
'name' => 'Name5',
'slug' => 'Name5'
]
]
]
]);
I want to filter this collection by headquarter and offer slug in order to get a Single offer
Right now i am trying using filter
$offer = $this->headquarters()
->filter(function($hq) use ($headquarter, $slug) {
return $hq['headquarter'] == $headquarter && $hq['offers']['slug'] == $slug;
});
But with no success.
Thanks for any advice
You can get all offers in specific headquarter with this code
$this->headquarters()->where('headquarter', 'Leon')[0]['offers'][0];
Then for each all offers
foreach ($this->headquarters()->where('headquarter', 'Leon')[0]['offers'] as $offer) {
print_r($offer);
}
or try this code
$offer = collect($this->headquarters()->where('headquarter', $headquarter)
->first()['offers'])
->where('slug', $slug)->first();
You $hq['offers'] is an array, you should access as $hq['offers'][0]['slug'].
$offer = $this->headquarters()
->filter(function($hq) use ($headquarter, $slug) {
return $hq['headquarter'] == $headquarter && in_array($slug, array_column($hq['offers'], 'slug'));
});

Categories