I am developing a system using Laravel 7.28.4
In the system I have created a SMSService to be able to send SMS message, below is the SMSService code
https://codeshare.io/aYjDRM
below is the code which the unit test read for the testing
<?php
namespace App\Services;
use App\Models\Booking;
use App\Traits\EmailTrait;
use App\Services\SMSService;
class BookingService extends BaseService
{
use EmailTrait;
public function update($input, $id)
{
$booking = Booking::find($id);
try {
$booking->update($input);
$sms_service = new SMSService;
$booking = Booking::whereId($id)->first();
$booking->update(['status' => config('staticdata.booking_status.success')]);
$this->sendBookingSuccessEmail($booking->applicantDetail->email, $booking->applicantDetail->first_name, $booking->reference_number);
$sms_service->sendBookingSuccessSMS($booking->applicantDetail->mobile_no, $booking->reference_number);
} catch (Exception $e) {
\Log::error($e);
return $this->formatGeneralResponse(
$e->getMessage(),
config('staticdata.status_codes.error'),
config('staticdata.http_codes.internal_server_error')
);
}
return $this->formatGeneralResponse(
config('staticdata.messages.update_success'),
config('staticdata.status_codes.ok'),
config('staticdata.http_codes.success')
);
}
}
external sources : https://codeshare.io/aVLAeR
during running unit test i am using Mockery to replicate the service behaviour
below is the code that i run for the unit test
<?php
namespace Tests\Api;
use App\Models\ApplicantDetails;
use App\Models\Booking;
use App\Models\Branch;
use App\Models\Province;
use App\Models\User;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Tests\TestCase;
use Laravel\Passport\Passport;
class BookingApiTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$user = factory(\App\Models\User::class)->create();
Passport::actingAs(
$user,
['frontend']
);
$response_data = [
'status' => [
'code' => '200',
'description' => 'asd'
]
];
$client = \Mockery::mock('overload:GuzzleHttp\Client');
$client->shouldReceive('post')
->andReturn($client)
->shouldReceive('getStatusCode')
->andReturn(200)
->shouldReceive('getBody')
->andReturn($client)
->shouldReceive('getContents')
->andReturn(json_encode($response_data));
}
public function createARandomDateBetweenRange($start, $end, $filter = null)
{
$period = CarbonPeriod::between($start, $end);
if ($filter) {
$period = $period->filter($filter);
}
return $period;
}
public function testMakeBookingSuccess()
{
$isWeekday = function ($date) {
return $date->isWeekday();
};
$period = $this->createARandomDateBetweenRange(Carbon::now()->format('Y-m-d'), '2021-12-31', $isWeekday);
$period = $period->toArray();
$book_date = $period[0]->format('Y-m-d');
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => factory(Branch::class)->create()->id,
'book_date' => $book_date,
'meridiem' => 'am'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertJsonStructure(
[
'status_code',
'message' => [
'encrypted_order_no',
'result',
'reference_number',
'booking_id'
]
]
);
}
public function testMakeBookingFailedOnWeekend()
{
$isWeekend = function ($date) {
return $date->isWeekend();
};
$period = $this->createARandomDateBetweenRange(Carbon::now()->format('Y-m-d'), '2021-12-31', $isWeekend);
$period = $period->toArray();
$book_date = $period[0]->format('Y-m-d');
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => factory(Branch::class)->create()->id,
'book_date' => $book_date,
'meridiem' => 'am'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'errors' => [
'book_date' => ['date cannot be in weekend']
]
]
);
}
public function testMakeBookingValidationFailed()
{
$data = [];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'branch' => 'The branch field is required.',
'meridiem' => 'The meridiem field is required.',
'province' => 'The province field is required.',
'book_date' => 'The book date field is required.',
'sso_id' => 'The sso id field is required.',
]
]
);
}
public function testMakeBookingSlotFullFailed()
{
$isWeekday = function ($date) {
return $date->isWeekday();
};
$period = $this->createARandomDateBetweenRange(Carbon::now()->format('Y-m-d'), '2021-12-31', $isWeekday);
$period = $period->toArray();
$book_date = $period[0]->format('Y-m-d');
$branch_id = factory(Branch::class)->create(
[
'slot_am' => 3,
'slot_pm' => 3,
]
)->id;
// am start
factory(Booking::class, 3)->create(
[
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'am',
]
);
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'am'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'errors' => [
'book_date' => ['Unable to book as the selected slot already full'],
]
]
);
// pm start
factory(Booking::class, 3)->create(
[
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'pm',
]
);
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'pm'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'errors' => [
'book_date' => ['Unable to book as the selected slot already full'],
]
]
);
}
public function testListBookingPortalSuccess()
{
$branch = factory(Branch::class)->create();
$data['sso_id'] = $branch->sso_id;
$response = $this->post(route('api.ph-portal.booking.list'), $data);
$response->assertJsonStructure(
[
'status_code',
'data'
]
);
}
public function testListBookingPortalNoDataFound()
{
factory(Branch::class)->create();
$data['sso_id'] = "#s3randomStringxde2sx" . rand(1, 100);
$response = $this->post(route('api.ph-portal.booking.list'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'data' => []
]
);
}
public function testListBookingSuccess()
{
$response = $this->get(route('api.booking.list'));
$response->assertJsonStructure(
[
'status_code',
'data',
]
);
factory(Booking::class)->create()->toArray();
$data = [
'per_page' => "5"
];
$response = $this->get(route('api.booking.list', $data));
$response->assertJsonStructure(
[
'status_code',
'data' => [
'current_page',
'data'
]
]
);
}
public function testViewBookingDetailsSuccess()
{
$booking = factory(Booking::class)->create(['sso_id' => '534534534589p345-5934543058405345']);
$response = $this->get(route('api.booking.details', $booking->id));
$response->assertJsonStructure(
[
'status_code',
'data' => [
'id',
'sso_id',
'user_id',
'province',
'branch',
'book_date',
'created_at',
'updated_at',
'meridiem',
'status',
'reference_number',
'applicant_detail',
'province_data',
'branch_data',
'transaction'
]
]
);
}
public function testViewBookingDetailsNoDataFound()
{
$response = $this->get(route('api.booking.details', 99999999999999999));
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'data' => null
]
);
}
public function testViewBookingDetailsPortalSuccess()
{
$booking = factory(Booking::class)->create();
$response = $this->get(
route(
'api.ph-portal.booking.details',
[
'sso_id' => $booking->sso_id,
'id' => $booking->id
]
)
);
$response->assertJsonStructure(
[
'status_code',
'data' => [
'id',
'sso_id',
'user_id',
'book_date',
'meridiem',
'status',
'reference_number',
'applicant_detail',
]
]
);
}
public function testViewBookingDetailsPortalValidationFailed()
{
$booking = factory(Booking::class)->create();
$response = $this->get(
route(
'api.ph-portal.booking.details',
[
'sso_id' => 999999999999999,
'id' => $booking->id
]
)
);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'sso_id' => 'The selected sso id is invalid.'
]
]
);
}
public function testBookingUpdateSuccess()
{
$booking = factory(Booking::class)->create();
$response_data = [
'umid' => 1,
'clientMessageId' => null,
'destination' => '+61212323',
'encoding' => 'GSM7',
'status' => [
'code' => '200',
'description' => 'asd'
]
];
$client = \Mockery::mock('overload:GuzzleHttp\Client');
$client->shouldReceive('post')
->andReturn($client)
->shouldReceive('getStatusCode')
->andReturn(200)
->shouldReceive('getBody')
->andReturn($client)
->shouldReceive('getContents')
->andReturn(json_encode($response_data));
$data = [
'branch' => factory(Branch::class)->create()->id,
'book_date' => '2020-12-01',
'meridiem' => 'am',
];
$response = $this->post(route('api.booking.update', $booking->id), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'message' => config('staticdata.messages.update_success')
]
);
}
public function testBookingUpdateValidationFailed()
{
$response = $this->post(route('api.booking.update', 9999999));
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'id' => 'The selected id is invalid.',
'branch' => 'The branch field is required.'
]
]
);
$booking = factory(Booking::class)->create();
$data = [
'branch' => factory(Branch::class)->create()->id,
'book_date' => '2020-12-01',
];
$response = $this->post(route('api.booking.update', $booking->id), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'meridiem' => 'The meridiem field is required when book date is present.'
]
]
);
}
public function testRequestNewBookingDateSuccess()
{
$booking = factory(Booking::class)->create();
$response = $this->post(route('api.ph-portal.booking.request_new_bookdate', $booking->id), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'message' => config('staticdata.messages.process_success')
]
);
}
}
external sources : https://codeshare.io/Gk6eDA
the unit test are able to run using this command
php artisan test --filter BookingApiTest
but error below appear during the unit test and i am unable to track on why this happen.
✕ booking update success
Tests: 1 failed, 11 passed, 5 pending
ErrorException
Undefined index: umid
at C:\laragon\www\nbi-backend\app\Services\SMSService.php:13
9| {
10| public function saveSMSData($data)
11| {
12| $data = [
> 13| 'umid' => $data['umid'],
14| 'client_message_id' => $data['clientMessageId'],
15| 'destination' => $data['destination'],
16| 'encoding' => $data['encoding'],
17| 'code' => $data['status']['code'],
1 C:\laragon\www\nbi-backend\app\Services\SMSService.php:13
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined index: umid", "C:\laragon\www\nbi-backend\app\Services\SMSService.php", [])
2 C:\laragon\www\nbi-backend\app\Services\SMSService.php:50
App\Services\SMSService::saveSMSData([])
i have tried using
php artisan tinker
then write the command as below
$sms = new SMSService
$sms->sendBookingSuccessSMS('601123456767','TEST123');
but the result came out as
null
kindly help on how to fix this issue or how to trace of how the problem occur
Thank you.
Some additional code info
config staticdata file
https://codeshare.io/5N8lgm
.env file
https://codeshare.io/aVLAB4
composer.json file
https://codeshare.io/G84Eev
Related
I would like to update a form, I mentioned that the form is already saved in the database(function store). I want to edit the form and update it in the database(function update).
I only want to UPDATE the "tags", this is giving me an error because it is in another table.
I would need your help because I can't do it, I tried different methods but didn't succeed.
public function store(Request $request)
{
// process the listing creation form
$validationArray = [
'title' => 'required',
'company' => 'required',
'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:9048',
'location' => 'required',
'service' => 'required',
'apply_link' => 'required|url',
'content' => 'required',
'payment_method_id' => 'required'
];
if (!Auth::check()) {
$validationArray = array_merge($validationArray, [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:5',
'name' => 'required',
'phone' => 'required|numeric|min:10|starts_with:0'
]);
}
$request->validate($validationArray);
// is a user signed in ? if not, create one and authenticate
$user = Auth::user();
if (!$user) {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone' => $request->phone
]);
$user->createAsStripeCustomer();
Auth::login($user);
}
// process the payment and create the listing
try {
$amount = 9900; // $99.00 USD in cents
if ($request->filled('is_highlighted')) {
$amount += 1000;
}
$user->charge($amount, $request->payment_method_id);
$md = new \ParsedownExtra();
$listing = $user->listings()
->create([
'title' => $request->title,
'slug' => Str::slug($request->title) . '-' . rand(1111, 9999),
'company' => $request->company,
'logo' => basename($request->file('logo')->store('public')),
'location' => $request->location,
'apply_link' => $request->apply_link,
'content' => $md->text($request->input('content')),
'is_highlighted' => $request->filled('is_highlighted'),
'is_active' => true
]);
**foreach (explode(',', $request->tags) as $requestTag) {
$tag = Tag::firstOrCreate([
'slug' => Str::slug(trim($requestTag))
], [
'name' => ucwords(trim($requestTag))
]);
$tag->listings()->attach($listing->id);
}**
foreach (explode(',', $request->service) as $requestService) {
$service = Service::firstOrCreate([
'service_name' => ucwords(trim($requestService))
]);
$service->listings()->attach($listing->id);
}
return redirect()->route('user.dashboard')->with('success', 'Anuntul tau a fost publicat!');
} catch (\Exception $e) {
return redirect()->back()
->withErrors(['error' => $e->getMessage()]);
}
} $tag->listings()->attach($listing->id);
}
public function edit($id)
{
$listing = Listing::findOrFail($id);
if (Auth::check() && Auth::user()->id == $listing->user_id) {
$listing = DB::table('listings')
->where('id', $id)
->first();
return view('listings.edit', compact('listing'));
} else {
return (redirect('/dashboard'));
}
}
public function update(Request $request, $id)
{
//working in progress...
$this->validate($request,[
'title' => 'required',
'company' => 'required',
'logo' => 'file|max:2048|required|mimes:jpeg,jpg,png',
'location' => 'required',
'apply_link' => 'required|url',
'content' => 'required'
// 'payment_method_id' => 'required'
]);
$data = Listing::find($id);
$data->title = $request->title;
$data->company = $request->company;
$data->logo = basename($request->file('logo')->store('public'));
$data->location = $request->location;
$data->apply_link = $request->apply_link;
$data['tags'] = explode(',', $request->tags); // <-this one
$data->content= $request->content;
// $data['is_highlighted'] = $request->is_highlighted;
$data['user_id'] = Auth::user()->id;
$data->save();
// DB::table('listings')->where('id', $id)->update($data);
return redirect()->back()->with('success', 'success');
}
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()
];
hope you are all doing well,
on my project, I faced an issue with posting data to an internal API, and keep getting cURL error 28 which means "Operation timed out after 30006 milliseconds with 0 bytes received"
BUT when I test the same API with the same values in POSTMAN it works fine, [Screenshot] -> https://tppr.me/hensp
And here is more details from laravel reports
https://flareapp.io/share/47q1Olz7#share
And my code is attached below.
Thanks in advance
public function addToCart($productId, array $options = [], $quantity = 1)
{
$this->product = Product::findOrFail($productId);
if (!Session::has('cart-token'))
Session::put('cart-token', Str::random(100));
$response = Http::post(env('APP_API_URL') . '/cart/store', [
'productId' => $this->product->id,
'quantity' => $quantity,
'options' => $options,
'cartToken' => Session::get('cart-token')
]);
$this->dispatchBrowserEvent('alert', [
'type' => $response['status'] ? 'success' : 'error',
'message' => $response['message']
]);
}
and the env variable is
APP_URL=127.0.0.1:8000
API_VERSION=1
APP_API_URL="${APP_URL}/api/v${API_VERSION}"
API controllers
public function addToCart(Request $request)
{
App::setLocale('en');
$request->validate([
'productId' => 'required|integer|exists:products,id',
'options' => 'array',
'options.*' => 'distinct|integer',
'quantity' => 'required|integer',
'cartToken' => 'nullable|string|max:191'
]);
$this->product = Product::findOrFail($request['productId']);
if ($request['quantity'] < 0)
$this->condition = true;
else
$condition = $this->conditions($request['options'] ?? [], $request['quantity']);
if ($this->conditionStatus) {
try {
$query = CartModel::where('cart_token', $request['cartToken'])
->where('product_id', $this->product->id)
->whereJsonContains('option_ids', $request['options'] ?? [])
->firstOrFail();
$query->update([
'quantity' => $query->quantity + $request['quantity']
]);
} catch (\Exception $e) {
$query = CartModel::create([
'cart_token' => $request['cartToken'],
'product_id' => $this->product->id,
'option_ids' => $request['options'] ?? [],
'quantity' => $request['quantity']
]);
}
return response()->json([
'status' => true,
'code' => 101,
'cart_token' => $query->cart_token,
'message' => trans('frontend/alert.cart.added_to_cart', ['product' => $this->product->detail->handleMultipleLanuage('title')])
]);
}
return response()->json($condition, 422);
}
public function conditions(array $options = [], $quantity)
{
$productOptions = ProductOption::where('product_id', $this->product->id)->get();
if ($productOptions) {
if (count($productOptions) != count($options))
return [
'status' => false,
'code' => 107,
'message' => trans('frontend/alert.cart.select_option')
];
$userCart = CartModel::where('option_ids', $options)->sum('quantity');
$productOptionLists = ProductOptionList::whereIn('id', $options)->get();
foreach ($productOptionLists as $listItem) {
if ($listItem->quantity == 0)
return response()->json([
'status' => false,
'code' => 102,
'message' => trans('frontend/alert.cart.out_of_stock', ['product' => $this->product->detail->handleMultipleLanuage('title')])
]);
if ($listItem->quantity < $userCart + $quantity)
return [
'status' => false,
'code' => 103,
'message' => trans('frontend/alert.cart.maximum_units')
];
}
}
if ($this->product->stock->quantity == 0 && $this->product->stock->quantity < $quantity)
return response()->json([
'status' => false,
'code' => 102,
'message' => trans('frontend/alert.cart.out_of_stock', ['product' => $this->product->detail->handleMultipleLanuage('title')])
]);
if ($this->product->stock->quantity < CartModel::where('product_id', $this->product->id)->sum('quantity') + $quantity)
return [
'success' => false,
'code' => 103,
'message' => trans('frontend/alert.cart.maximum_units')
];
$this->conditionStatus = true;
}
I use api platform to create api rest but in configuration package i found this error.
enter image description here
I copie and paste this code in documentation :
https://api-platform.com/docs/core/jwt/#adding-endpoint-to-swaggerui-to-retrieve-a-jwt-token
and this is my code:
<?php
declare(strict_types=1);
namespace App\Swagger;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class SwaggerDecorator implements NormalizerInterface
{
/**
*
* #var NormalizerInterface
*/
private NormalizerInterface $decorated;
public function __construct(NormalizerInterface $decorated)
{
$this->decorated = $decorated;
}
public function supportsNormalization($data, string $format = null): bool
{
return $this->decorated->supportsNormalization($data, $format);
}
public function normalize($object, string $format = null, array $context = [])
{
$docs = $this->decorated->normalize($object, $format, $context);
$docs['components']['schemas']['Token'] = [
'type' => 'object',
'properties' => [
'token' => [
'type' => 'string',
'readOnly' => true,
],
],
];
$docs['components']['schemas']['Credentials'] = [
'type' => 'object',
'properties' => [
'username' => [
'type' => 'string',
'example' => 'api',
],
'password' => [
'type' => 'string',
'example' => 'api',
],
],
];
$tokenDocumentation = [
'paths' => [
'/authentication_token' => [
'post' => [
'tags' => ['Token'],
'operationId' => 'postCredentialsItem',
'summary' => 'Get JWT token to login.',
'requestBody' => [
'description' => 'Create new JWT Token',
'content' => [
'application/json' => [
'schema' => [
'$ref' => '#/components/schemas/Credentials',
],
],
],
],
'responses' => [
Response::HTTP_OK => [
'description' => 'Get JWT token',
'content' => [
'application/json' => [
'schema' => [
'$ref' => '#/components/schemas/Token',
],
],
],
],
],
],
],
],
];
return array_merge_recursive($docs, $tokenDocumentation);
}
}
As explained in the error message, your method normalize shall be exactly the same as it was declared in the interface.
Replace:
public function normalize($object, string $format = null, array $context = [])
By:
public function normalize($object, $format = null, array $context = [])
replace:
public function normalize($object, string $format = null, array $context = [])
by:
public function normalize(mixed $object, ?string $format = null, array $context = []);
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)[],
];
});