Home > Enterprise >  Code optimization and alternative method to handle this
Code optimization and alternative method to handle this

Time:07-11

 public function store(StoreWorkerRequest $request){    
    $attributes = $request->validated();
    $worker = DB::transaction(function () use ($attributes) {
        $worker = Worker::create($attributes);
        $course = $worker->course()->create(['course_name' => $attributes['course_name']]);
        $media = $course->media()->create(["filename" => fileUpload($attributes['doc_file'], 'Course'),"filetype" => "pdf"]);
        $medical_data = $worker->medical_detail()->create(['expiry_date' => $attributes['expiry_date']]);
        $document = $worker->document()->create(['doc_name' => $attributes['doc_name']]);
        return $worker
    });
    return success(new WorkerResource($worker), __('Workers created successfully'));

}

 THis is my StoreWorkerRequest
 return [
        'first_name' => ['required', 'string'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:workers,email'],
        'last_name' => ['required', 'string'],
        'phone_number' => ['nullable', 'numeric'],
        'hourly_rate' => ['required', 'numeric'],
        'birth_date' => ['required','date'],
        'doc_file' => ['sometimes','file','mimes:jpeg,png,jpg,doc,docx,pdf,csv,xlsx'],
        'course_file' => ['sometimes','file','mimes:jpeg,png,jpg,doc,docx,pdf,csv,xlsx'],
        'medical_file' => ['sometimes','file','mimes:jpeg,png,jpg,doc,docx,pdf,csv,xlsx'],
        'course_name' => ['sometimes','string'],
        'doc_name' => ['sometimes','string'],
        'medical_name' => ['sometimes','string'],
        'expiry_date' => ['sometimes','date'],
    ];
}

. I am working this way. It it a good practice? media is a has many polymorphic relationship with course, medical_detail and document. and worker has One relationship with course, medical_detail and document. The problem here I found was , It gives error if any one the attribute field is missing, and also if if course create fails, then media->course()-> will give error? What will be a better approach? and does this approach effect performance? Came here for code optimization

CodePudding user response:

All seems right except one moment. Your transaction doesn't have return, so the result will be null. You should do like so:

public function store(StoreWorkerRequest $request){    
    $attributes = $request->validated();
    $worker = DB::transaction(function () use ($attributes) {
        $worker = Worker::create($attributes);
        $course = $worker->course()->create(['course_name' => $attributes['course_name']]);
        $media = $course->media()->create(["filename" => fileUpload($attributes['doc_file'], 'Course'),"filetype" => "pdf"]);
        $medical_data = $worker->medical_detail()->create(['expiry_date' => $attributes['expiry_date']]);
        $document = $worker->document()->create(['doc_name' => $attributes['doc_name']]);

        return $worker;
    });
    return success(new WorkerResource($worker), __('Workers created successfully'));
}

Everything other is okay. Transactions are designed to throw an error when at least one query was unsuccessful.

CodePudding user response:

You can use try catch like this:

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

Look at this:

Laravel: Using try...catch with DB::transaction()


Or you can use optional helper:

$course = optional($worker->course())->create[];

See this artical:

How does Laravel optional() work?

  • Related