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');
}
So, I'm trying to make update function, using this
public function editProfile(Request $request, $id)
{
// Validating
$request->validate([
// 'username' => 'nullable|unique:users|min:4',
// 'email' => 'nullable|unique:users|email:rfc,dns',
'contact_phone' => 'nullable|digits_between:9,12',
'bio_en' => 'nullable',
'bio_ar' => 'nullable',
'icon' => 'nullable',
'logo' => 'nullable',
'plan_id' => 'required',
'category_id' => 'required',
'is_local' => 'required',
]);
$user = User::find($id);
$user->update([
'username' => $request->username,
'email' => $request->email,
'contact_phone' => $request->contact_phone,
'bio_en' => $request->bio_en,
'bio_ar' => $request->bio_ar,
'logo' => $request->logo,
'icon' => $request->icon,
'plan_id' => $request->plan_id,
'category_id' => $request->category_id,
'referred_by_id' => Auth::user()->id,
]);
if ($user) {
return back()->with("success", __("editedSuccessfully"));
} else {
return back()->with('error', __("somethingWentWrongTryAgainLater"));
}
}
but I get the error
Call to a member function update() on null
shows on line $user->update
hope anyone can help me
It returns null because it cannot find the user with User::find($id). Check that you have a user by $id
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
How to optimize in_array in my function?
I tried isset but it doesn't work.
public function index() {
$this->checkPermission();
$banks = BankAccount::all();
$clients = Role::whereRoleSlug('client')
->firstOrFail()
->users;
$projects = Project::whereProjectStatus('active')->get();
$adminBanks = BankAccount::where('bank_user_id', '=', null)->get();
$roles = Role::whereIn('role_slug', ['administrator', 'accountant'])
->pluck('role_id')
->toArray();
$cash = 0;
$payments = Payment::wherePaymentBy('cash')->get();
/*->filter(function ($payment) {
return in_array($payment->activity->activityBy->id, $roles)
});*/
foreach ($payments as $index => $payment) {
if(in_array($payment->activity->activityBy->role_id, $roles)) {
if(in_array(strtolower($payment->payment_purpose), ['employee_transfer', 'employee_refund', 'vendor_payment', 'vendor_refund', 'loan_payment', 'salary', 'office_deposit'])) {
$cash -= $payment->payment_amount;
}
else {
$cash += $payment->payment_amount;
}
}
}
// foreach ($payments as $index => $payment) {
// if (isset($payment->activity->activityBy->role_id, $roles)) {
// if (isset($payment['employee_transfer'], $payment['employee_refund'], $payment['vendor_payment'], $payment['vendor_refund'], $payment['loan_payment'], $payment['salary'], $payment['office_deposit'])) {
// $cash -= $payment->payment_amount;
//// dd($roles);
// } else {
// $cash += $payment->payment_amount;
// }
// }
// }
return view('admin.accounting.banks.index')
->with([
'adminBanks' => $adminBanks,
'banks' => $banks,
'clients' => $clients,
'projects' => $projects,
'cash' => $cash
]);
}
public function bankDetails($id) {
if(!Auth::user()->isAdmin() && !Auth::user()->isAccountant()) {
return redirectBackWithNotification('error', 'You are not authorised!');
}
if($id == 'cash') {
$projects = Project::select(['bsoft_projects.project_id', 'bsoft_projects.project_name'])->get();
return view('admin.accounting.banks.show')
->with([
'projects' => $projects
]);
}
$bank = BankAccount::findOrFail($id);
if(!$bank->user) {
$payments = Payment::where('payment_from_bank_account', '=', $bank->bank_id)
->orWhere('payment_to_bank_account', '=', $bank->bank_id)
->get();
$balance = $bank->bank_balance;
}
else {
$payments = Payment::where('payment_from_bank_account', '=', $bank->bank_id)
->orWhere('payment_to_bank_account', '=', $bank->bank_id)
->orWhere('payment_to_user', '=', $bank->user->id)
->orWhere('payment_from_user', '=', $bank->user->id)
->get();
$balance = 0;
$exp = 0;
$inc = 0;
foreach ($payments as $payment) {
if($payment->payment_from_user == $bank->user->id) {
$exp += $payment->payment_amount;
}
elseif ($payment->payment_to_user == $bank->user->id) {
$inc += $payment->payment_amount;
}
}
$balance = $inc - $exp;
}
return view('admin.accounting.banks.show')
->with([
'bank' => $bank,
'payments' => $payments,
'balance' => $balance
]);
}
public function rechargeFromCustomer(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'user_id' => ['required', 'numeric'],
'bank_id' => ['nullable', 'numeric'],
'project_id' => ['required', 'numeric'],
'type' => ['required', 'string'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$payment = createNewPayment([
'type' => 'credit',
'to_user' => null,
'from_user' => $request->post('user_id'),
'to_bank_account' => (strtolower($request->post('type')) === 'bank' || strtolower($request->post('type')) === 'check')
? $request->post('bank_id') : null,
'from_bank_account' => null,
'amount' => $request->post('amount'),
'project' => $request->post('project_id'),
'purpose' => 'project_money',
'by' => $request->post('type'),
'date' => $request->post('date'),
'image' => null,
'note' => $request->post('note')
]);
if(!$payment) {
return redirectBackWithNotification();
}
if(strtolower($request->post('type')) === 'bank' || $request->post('type') == 'check') {
$offBank = BankAccount::findOrFail($request->post('bank_id'));
$offBank->bank_balance = $offBank->bank_balance + (float) $request->post('amount');
$offBank->save();
}
return redirectBackWithNotification('success', 'Client Money Successfully Received!');
}
public function storeAccount(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'user_id' => ['nullable', 'numeric'],
'name' => ['required', 'string'],
'number' => ['required', 'string'],
'bank' => ['required', 'string'],
'branch' => ['required', 'string'],
'balance' => ['required', 'numeric'],
'accountFor' => ['required', 'string'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$bank = new BankAccount();
$bank->bank_user_id = ($request->post('user_id')) ? $request->post('user_id') : null;
$bank->bank_account_name = $request->post('name');
$bank->bank_account_no = $request->post('number');
$bank->bank_name = $request->post('bank');
$bank->bank_branch = $request->post('branch');
$bank->bank_balance = $request->post('balance');
if(!$bank->save()) {
return redirectBackWithNotification();
}
addActivity('bank', $bank->bank_id, 'Bank Account Added');
return redirectBackWithNotification('success', 'Bank Account Successfully Added!');
}
public function transferToEmployee(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'employee_id' => ['required', 'string'],
'bank_id' => ['nullable', 'numeric'],
'project_id' => ['required', 'numeric'],
'type' => ['required', 'string'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
if(strtolower($request->post('type')) !== 'cash' && $request->post('bank_id') === null) {
return redirectBackWithNotification('error', 'Bank Account must be selected!');
}
$employee_id = $request->post('employee_id');
$employee_bank_id = null;
if(strpos($request->post('employee_id'), '#') !== false) {
$employee_id = Str::before($request->post('employee_id'), '#');
$employee_bank_id = Str::after($request->post('employee_id'), '#');
}
$paymentData = [
'type' => null,
'to_user' => $employee_id,
'from_user' => Auth::id(),
'to_bank_account' => $employee_bank_id,
'from_bank_account' => (strtolower($request->post('type')) !== 'cash') ? $request->post('bank_id') : null,
'amount' => $request->post('amount'),
'project' => $request->post('project_id'),
'purpose' => 'employee_transfer',
'by' => strtolower($request->post('type')),
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
if(strtolower($request->post('type')) === 'bank' || $request->post('payment_by') == 'check') {
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance - (float) $request->post('amount');
$officeBank->save();
$employeeBank = BankAccount::findOrFail($employee_bank_id);
$employeeBank->bank_balance = $employeeBank->bank_balance + (float) $request->post('amount');
$employeeBank->save();
}
return redirectBackWithNotification('success', 'Transfer successfully made!');
}
public function transferToOffice(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'employee_id' => ['required', 'string'],
'bank_id' => ['nullable', 'numeric'],
'project_id' => ['required', 'numeric'],
'type' => ['required', 'string'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
if(strtolower($request->post('type')) !== 'bank' && $request->post('bank_id') === null) {
return redirectBackWithNotification('error', 'Bank Account must be selected!');
}
$employee_id = $request->post('employee_id');
$employee_bank_id = null;
if(strpos($request->post('employee_id'), '#') !== false) {
$employee_id = Str::before($request->post('employee_id'), '#');
$employee_bank_id = Str::after($request->post('employee_id'), '#');
}
else {
$employee_bank_id = $this->createAutoGeneratedAccount($employee_id)->bank_id;
}
$paymentData = [
'type' => null,
'to_user' => $employee_id,
'from_user' => null,
'to_bank_account' => $employee_bank_id,
'from_bank_account' => (strtolower($request->post('type')) === 'bank') ? $request->post('bank_id') : null,
'amount' => $request->post('amount') - ($request->post('amount') * 2),
'project' => $request->post('project_id'),
'purpose' => 'employee_refund',
'by' => strtolower($request->post('type')),
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
if(strtolower($request->post('type')) === 'bank' || $request->post('payment_by') == 'check') {
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance + (float) $request->post('amount');
$officeBank->save();
}
$employeeBank = BankAccount::findOrFail($employee_bank_id);
$employeeBank->bank_balance = $employeeBank->bank_balance - (float) $request->post('amount');
$employeeBank->save();
return redirectBackWithNotification('success', 'Money successfully refunded!');
}
public function withdrawFromBank(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'bank_id' => ['nullable', 'numeric'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$paymentData = [
'type' => null,
'to_user' => null,
'from_user' => null,
'to_bank_account' => null,
'from_bank_account' => $request->post('bank_id'),
'amount' => $request->post('amount'),
'project' => null,
'purpose' => 'office_withdraw',
'by' => 'cash',
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance - (float) $request->post('amount');
$officeBank->save();
return redirectBackWithNotification('success', 'Money successfully Withdrawn!');
}
public function depositToBank(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'bank_id' => ['nullable', 'numeric'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$paymentData = [
'type' => null,
'to_user' => null,
'from_user' => null,
'to_bank_account' => $request->post('bank_id'),
'from_bank_account' => null,
'amount' => $request->post('amount'),
'project' => null,
'purpose' => 'office_deposit',
'by' => 'cash',
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance + (float) $request->post('amount');
$officeBank->save();
return redirectBackWithNotification('success', 'Money successfully Deposited!');
}
public function income() {
$this->checkPermission();
$projects = Project::select(['bsoft_projects.project_id', 'bsoft_projects.project_name'])->get();
return view('admin.accounting.income')
->with([
'projects' => $projects
]);
}
public function expense() {
$this->checkPermission();
$projects = Project::select(['bsoft_projects.project_id', 'bsoft_projects.project_name'])->get();
return view('admin.accounting.expense')
->with([
'projects' => $projects
]);
}
public function getUsers(Request $request) {
$this->checkPermission();
$users = Role::whereRoleSlug($request->post('type'))->firstOrFail()
->users;
return view('admin.accounting.banks.ajax-users')
->with([
'users' => $users
]);
}
public function getClientProjects(Request $request) {
$this->checkPermission();
$projects = User::findOrFail($request->post('client_id'))->clientProjects()
->where('project_status', '=', 'active')->get();
return view('admin.accounting.banks.ajax-projects')
->with([
'projects' => $projects
]);
}
public function getManagers(Request $request) {
$this->checkPermission();
$roles = Role::whereIn('role_slug', ['manager'])
->pluck('role_id')
->toArray();
$users = Project::findOrFail($request->post('project_id'))->employees()
->whereIn('role_id', $roles)
->get();
return view('admin.accounting.banks.ajax-employees')
->with([
'users' => $users
]);
}
/**
* #return bool|\Illuminate\Http\RedirectResponse
*/
protected function checkPermission() {
$role = Auth::user()->role->role_slug;
if($role == 'administrator' || $role == 'accountant') {
return true;
}
return redirectBackWithNotification('error', 'Sorry! You Are Not Authorised!.');
}
protected function createAutoGeneratedAccount(int $id) {
$employee = User::findOrFail($id);
$bank = new BankAccount();
$bank->bank_account_name = 'Auto Generated Bank Account!';
$bank->bank_user_id = $employee->id;
$bank->save();
return $bank;
}
It take about 4/5m to load, i try in localhost but it say 60s timeout error.i want to load this page within 30s. i can't optimize in_array in in_array($payment->activity->activityBy->role_id, $roles) and
in_array(strtolower($payment->payment_purpose), ['employee_transfer', 'employee_refund', 'vendor_payment', 'vendor_refund', 'loan_payment', 'salary', 'office_deposit'])
Mainly those two if occur loading time error.
can i optimize in_array in $payment and what is the problem in role_id in $roles? and why it take so many time to load my page?
And is there any way to Optimize bankDetails function because it take also 3/4m to load All, Loan and by Project details information?
If you are searching for a key in an array I would recommend you using array_key_exists which checks if the given key or index exists in the array (checks in keys, not in values) and returns true, or false because in_array you have checks if a value exists in an array (checks the values, not the keys) and returns true, or false.
What is the difference between in_array() and array_key_exists()?
You could try moving some more of the filtering to the database and decreasing the need to load the relationships for all the models:
$payments = Payment::wherePaymentBy('cash')
->whereHas('activity.activityBy', function ($query) use ($roles) {
$query->whereIn('role_id', $roles);
})->get();
Then you can remove if(in_array($payment->activity->activityBy->role_id, $roles)). This should also remove a N+1 problem of dynamically loading the relationships for all those models (lazy loading) and their relationships and their relationships. Also removing any overhead of having to hydrate many unneeded models.
Assuming that is a chain of relationships you are working down to get to role_id.
Laravel 5.8 Docs - Eloquent - Relationships - Querying Relationship Existence whereHas
I'm using laravel 5.2 and i'm using Form Request that given by laravel vendor to make my code clean, so i don't have many code on my controller :
public function store( CouponRequest $request )
{
DB::beginTransaction();
try {
$coupon = Coupon::create( $request->all() );
DB::commit();
return redirect()->route('admin.coupons.index');
} catch (\Exception $e) {
DB::rollback();
return redirect()->back()->withInput();
}
And this is my sample code about my request form :
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
Where should i place this command? :
$start_date = Carbon::create( $request->start_year, $request->start_month, $request->start_day );
$start_date->setTimeFromTimeString( $request->start_time );
$finish_date = Carbon::create( $request->finish_year, $request->finish_month, $request->finish_day );
$finish_date->setTimeFromTimeString( $request->finish_time );
If i place this code before validation, i could be error when some field not filled well by users.
So what i want is to place this code after validation success, but i don't want to place it at my controller.
Is there FormRequest function that can be called after validation success to modify my request??
I think it's not good when there's much code at controller, so i want to minimalize my controller code.
I am going to attempt this using FormRequest. If the intention here is to both validate and assign start_date and finish_date, this is probably the plausible way of doing so in Laravel:
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
/**
* #inheritDoc
*
* This method overrides Laravel's defeault FormRequest
* to create validator with `after()` hook
*/
protected function validator($validator)
{
$validator
->make(
$this->validationData(), $this->rules(), $this->messages(), $this->attributes()
)
->after(function($validator) {
if ($date = $this->getCarbonInstanceFromPrefix('start')) {
$request->start_date = $date;
} else {
$validator->errors()
->add('start_year', 'Invalid starting date and time');
}
if ($date = $this->getCarbonInstanceFromPrefix('finish')) {
$request->finish_year = $date;
} else {
$validator->errors()
->add('finish_year', 'Invalid finish date and time');
}
});
}
/**
* Retrieve carbon instance from current request, using prefix
*
* #param string $prefix
*
* #return Carbon|null
*/
protected function getCarbonInstanceFromPrefix($prefix = '')
{
try {
$date = Carbon::create(
$request->get($prefix . '_year'),
$request->get($prefix . '_month'),
$request->get($prefix . '_day')
);
$date->setTimeFromTimeString( $request->get($prefix . '_time') );
return $date;
} catch (\Exception $e) {
return null;
}
}
Quick Explanation
FormRequest essentially extends from Illuminate\Foundation\Http\FormRequest and can override the method where instance of Validator is created. By creating your custom validator, you can attach after() event to both validate each date inputs, and also assign additional parameter to request in one go.