Reputation: 6355
Hi I am creating an array which will store sections in my site. Some of these sections will not be available for some users to view therefore I will need to check the permission of the user in question before putting into my array. However when I do this if statement I get an array within an array which I don't want and this causes the following error:
Method Illuminate\View\View::__toString() must not throw an exception
This is the code I am using:
$user = Auth::user();
if(($user->hasRole('Admin') || $user->hasRole('Admin') || $user->hasRole('Project Master') || $user->hasRole('Project Owner'))) {
$restrictsections = ['Create' => route('project.create'),
'Sort' => route('project.sort'),];
}
$this->sections = [
'Projects' => [
'View' => route('project.index'),
$restrictsections
]
];
The array is now structured as so:
array(1) {
["Projects"]=>
array(2) {
["Create"]=>
string(30) "http://projects.local/projects"
[0]=>
array(2) {
["Create"]=>
string(37) "http://projects.local/projects/create"
["Edit"]=>
string(35) "http://projects.local/projects/sort"
}
}
}
As opposed to:
$this->sections = [
'Project' => [
'View' => route('project.index'),
'Create' => route('project.create'),
'Sort' => route('project.sort'),
]
];
array(1) {
["Project"]=>
array(3) {
["View"]=>
string(30) "http://projects.local/project"
["Create"]=>
string(37) "http://projects.local/project/create"
["Sort"]=>
string(35) "http://projects.local/project/sort"
}
}
Any ideas how I can merge the two arrays together? but it should be structured as follows:
array(1) {
["Project"]=>
array(3) {
["View"]=>
string(30) "http://projects.local/project"
["Create"]=>
string(37) "http://projects.local/project/create"
["Sort"]=>
string(35) "http://projects.local/project/sort"
}
}
Upvotes: 2
Views: 789
Reputation: 4043
Use array_merge()
like this
$this->sections = [
'Projects' => array_merge(
['View' => route('project.index')],
$restrictsections
)
];
or use the +
operator like this
$this->sections = [
'Projects' => ['View' => route('project.index')] + $restrictsections
];
Upvotes: 1
Reputation: 6893
You can use the +
operator to combine arrays.
For example:
php > print_r(['View' => '1'] + ['Create' => 'two', 'Sort' => '3']);
Array
(
[View] => 1
[Create] => two
[Sort] => 3
)
Applying to your code:
$user = Auth::user();
if(($user->hasRole('Admin') || $user->hasRole('Admin') || $user->hasRole('Project Master') || $user->hasRole('Project Owner'))) {
$restrictsections = ['Create' => route('project.create'),
'Sort' => route('project.sort'),];
}
$this->sections = [
'Projects' => [
'View' => route('project.index')
] + $restrictsections
];
edit: +
is technically a union so if the second array has keys that are present in the first array they will be ignored.
Upvotes: 1
Reputation: 26153
Create it a little another
$this->sections = ['Projects' => $restrictsections];
$this->sections['Projects']['View'] = route('project.index');
Upvotes: 1