I am unable to write a code to get object for another function.
I have one class called RepairsService
where I have two functions.
First createRepair($request, $vehicle)
is where I create object.
public function createRepair($request, $vehicle)
{
DB::transaction(function () use ($request, $vehicle) {
Log::info('Creating new repair.');
$repair = new Repair();
$repair->vehicle_id = $vehicle->id;
DB::insert('insert into repairs (vehicle_id) values (?)',
[$repair->vehicle_id]);
});
$this->addRepair($request, $vehicle, $this); //here I call second function trying to pass $this parameter as object
}
And second in the same class is
public function addRepair($request, $vehicle, $repair){
DB::transaction(function () use ($request, $vehicle, $repair) {
$workers_needed->repair_id = $repair->id; //I need to get this id from the object
$workers_needed->worker_id = $request->worker_id;
DB::insert('insert into repair_worker (repair_id, worker_id) values (?, ?)',
[$workers_needed->repair_id, $workers_needed->worker_id]);
Log::info('Repair created.');
flash('Repair successfully added.', 'success');
});
}
What am I doing wrong? Right now using this code, I am getting error
Undefined property: App\Models\Repairs\RepairsService::$id
what makes sense, since I am not passing object (I think).
UPDATE:
So the main problem described above is fixed in the following code, but I am heading a very little problem now. In the second function, I am trying to assign $repair-id
to $workers_needed->repair_id
but I get NULL
value there. I have tried to assign value 1
(hard coded) instead of using $repair-id
but it seems that my second function call runs before the first function is done with transaction
which makes sense, because as far as I know, transaction
inserts data only if everything goes well and in this case, it is waiting for second function to get its work done. So the repair
instance is not inserted into database. How can I edit the code so the transaction gets done and then I call my second function? Or is there another way how to do it?
public function createRepair($request, $vehicle)
{
$repair = null;
DB::transaction(function () use ($request, $vehicle, $repair) {
Log::info('Creating new repair.');
$repair = new Repair();
$repair->vehicle_id = $vehicle->id;
DB::insert('insert into repairs (vehicle_id) values (?)',
[$repair->vehicle_id]);
$this->addRepairWorker($request, $vehicle, $repair);
});
}
public function addRepairWorker(Request $request , Vehicle $vehicle, Repair $repair){
$workers_needed = null;
DB::transaction(function () use ($request, $vehicle, $repair) {
Log::info('Creating new repair worker instance.');
$workers_needed = new Repair_worker();
$workers_needed->repair_id = $repair->id;
$workers_needed->worker_id = $request->worker_id;
DB::insert('insert into repair_worker (repair_id, worker_id) values (?, ?)',
[$workers_needed->repair_id, $workers_needed->worker_id]);
Log::info('Repair created.');
flash('Repair successfully added.', 'success');
});
}