Storing Multiple Data in Laravel - laravel

I am trying to think of a way that a user can add a type(medical) on the frontend but a verifier has to approve that record? i can't seem to figure out the best solution for this, does anyone have any suggestions on how to make this work? It's getting stored in the medical table but not in Verifier table.
In Simple words, I am using the medicalRecord Controller to stored medical and Verifier details.
'document_id' = the medical_id;
'submitted_by' = who created the record
public function store Request $request, $id)
{
if (auth_user_cannot(Capability::CREATE_DRIVER_MEDICAL_RECORD)) {
return redirect($group['name'] . "/" . $group['userId']);
}
$all = $request->all();
if ($request->hasFile('myfile')) {
$result = upload($request->file('myfile'), 'nonzip', 'Medical');
$all['upload'] = $result['upload'];
$all['uploadId'] = $result['uploadId'];
}
// u'll need to save the medical to the user first, then save the verifier to the medical.
$driverMedical = DriverMedicalRecord::create($all);
// Then for the relation;
$medical = $driverMedical->find($id);
$verificationData = DocumentVerification::create( [
'document_id' => $medical,
'submitted_by'=> Auth::id(),
]) ;
$request->user()->posts()->save($post);
$driverMedical->verifier()->save($verificationData);

set a flag in the same table and change its value when it got verified.
ex: is_verfied it should be 0 when it is not approved when it got approved change it to 1 (this is what i understand from your question)

Related

Error: Multiple databases for CI4 and its uses default database as object validation in inserting data

By the way, this is not really a question. I just want really to share how to validate using a specific database in multiple database connections. Since I got this error and it took almost 2 days and thank you to the members of the Codeigniter 4 community who help me how to solve it.
I would like to share it also here for future references if someone encounters this error. Shout out to kenjis for the help!
At first, I thought it was just a bug in the codeigniter4 that if I have a multiple database connections the validation rules only use the default DB group. But unfortunately, No. I just don't specify what DB group I should verify.
In case you encounter this error, just add this on your controller:
protected function validate($rules, array $messages = []): bool
{
$this->validator = \Config\Services::validation();
// If you replace the $rules array with the name of the group
if (is_string($rules)) {
$validation = config('Validation');
// If the rule wasn't found in the \Config\Validation, we
// should throw an exception so the developer can find it.
if (! isset($validation->{$rules})) {
throw ValidationException::forRuleNotFound($rules);
}
// If no error message is defined, use the error message in the Config\Validation file
if (! $messages) {
$errorName = $rules . '_errors';
$messages = $validation->{$errorName} ?? [];
}
$rules = $validation->{$rules};
}
return $this->validator->withRequest($this->request)->setRules($rules, $messages)->run(null, null, 'other-db-group-name');
}
reference: https://github.com/codeigniter4/CodeIgniter4/issues/5654

Update Laravel model from external API

I have a Coin model with id,name,price.
In a function, I extract all the coins and create a comma separated string with all the ids:
$coins = Coin::all();
$coinsIds = $coins->pluck('id')->toArray();
$coinsIdsString = implode(',', $coinsIds);
After that I make a call to an external API:
$url = 'https://myapi.com?ids' . $coinsIdsString;
$response = Http::get($url)->json();
$response value is an array of coins, something like:
[
{
"id":"1",
"name":"A",
"price":"1.2",
},
...
]
What would be the best way to update and save my Coin model with the price value from API?
Unfortunately, you're not going to be able to do anything other than update a single record at a time. That is, loop through the results of the array and perform a database update on each record. My recommendation is
$results = ... // Result of API call;
foreach ($results as $result) {
DB::table('coins')
->where('id', $result['id'])
->update(['price' => $result['price']]);
}
I would then create a scheduled command to periodically perform the update since it is likely to be resource intensive depending on the volume of calls.
https://laravel.com/docs/8.x/scheduling#scheduling-artisan-commands

should i put this code in the model or controller in laravel

ok so I am upping my Laravel and MVC skills..currently all this in the controller (i know its bad thats why I am here I am trying to do it better :D)
Receive Data from UI as post (Done)
I have to store a file (Done)
store that file ID and path in a Files Table (Done)
Create new record and use the above record ID using query builder(Done)
but should I keep this in the controller or does this belong in the model specificlaly getting the files and storing the record etc.
do i build it the long way in the controller and use save()?
or return from a new model for files and pass that through on return (this i feel is best way ).
FileModel (To be built)
saves files returns file ID from file table
Business Model saves buisness data
controllerfile:
use /app/fileModel
$fileStored = call file model and passes request->file
for storing
$businessFile = $fileStored;
Save()
I think I have answered my own question but I am just making sure.
I am known for coding in anti patterns so I am asking for a bit of guidance not code thank you
Also if anyone knows of a place to just discuss laravel stuff so not to put here I would love a a good conversation, some my questions may seem stupid, I just need a soundboard at times.
ok so this works and is my solution.
public function create(Request $request)
{
//get files from request
$Match1 = $request->file('Match1')->store('media/scores');
$Match2 = $request->file('Match2')->store('media/scores');
$Match3 = $request->file('Match3')->store('media/scores');
//build collection array to loop through saving them
$collection = collect([$Match1,$Match2,$Match3]);
// store return paths in to new array
$mediapaths = array();
//loop through collections saving details in to files table pushing to the paths array
foreach($collection as $MatchScore) {
$ScoresSaved = Files::create([
'user_id' => $request->userID,
'file_name' => $request->title,
'type' => 'png',
'category_id'=>3,
'path' => $MatchScore,
'is_public'=>0
]);
array_push($mediapaths, $ScoresSaved);
}
//Save the score with new media path to the model
$scores = new Scores;
$scores->tournament=22;
$scores->round='Finals';
$scores->homeArcade=2578;
$scores->homePlayer=2;
$scores->opponenet=2;
$scores->Match1=$mediapaths[0]['id'];
$scores->Match2=$mediapaths[1]['id'];
$scores->Match3=$mediapaths[2]['id'];
$scores->Match1Score=22;
$scores->Match2Score=44;
$scores->Match3Score=88;
$scores->comments='testing full flow';
$scores->winner=2;
$scores->referee=3;
$scores->confirmed=1;
$scores->dispute=0;
$scores->submitedBy=2;
$scores->save();
return response()->json([
'result' => 'Success'
]);
}

How to handle data before delete from model in Laravel?

I have the following method:
public function destroy($id)
{
$id = \JWTAuth::parseToken()->authenticate();
$offer = Offer::findOrFail($id);
$offer->delete();
return response()->json(["offer" => $offer]);
}
How handle data before deleting? I need to check if user has permit to delete data or not
When you use the authenticate() method, the user model is retrieved so it means the id you have is not an id but a User. Have you checked the documentation of JWT Because first and foremost you have to retrieve the user and this is sufficient:
$user = \JWTAuth::parseToken()->authenticate();
Then if you have a field for example in your users table to tell if the user have the right say admin which can be 1 or 0 then you can do the following:
if($user->admin == 1)
{
$offer = Offer::findOrFail(1); //say id
$offer->delete();
return response()->json(["offer" => $offer]);
}
return response()->json(['error' => 'you dont have the right to delete this'], 403);
Just a little scratch on the idea, but my best advice is to do some searches on how JWT is implemented, I am pretty sure you will find tons of them online.
I would recommend using the Model's delete event:
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L1122
and handle it.
This will guarantee that if you use the delete method on a model, you always check permissions.

Laravel: two models in one controller method

Let me explain about my problem.
I am currently using Laravel 5.0. Here is my structure
Table: bgts, Model: Bgt, Controller: BgtController
Table: bgthistories, Model: BgtHistory
Now I want to do these:
Everytimes creating new item into bgts table, I want to make a copy and insert into bgthistories table. Then, everytimes that record is updated, i'll copy one more version, still insert into bgthistories.
Here is store() method.
public function store(Request $request) {
$bgt = new Bgt();
$history = $this->coppy($bgt);
$uploader = new UploadController('/data/uploads/bgt');
$bgt->name = $request['name'];
$bgt->avatar = $uploader->avatar($request);
$bgt->attachments($uploader->attachments($request));
//dd($bgt);
$bgt->save();
$history->save();
return redirect('bgt');
}
And this is the coping:
public function coppy($bgt) {
$array = $this->$bgt->toArray();
$version = new BgtHistory();
foreach($array as $key => $value) {
$version->$key = $value;
}
return $version;
}
I create migration tables already. Everything is ready. But, when I call
$bgt->save();
$history->save();
It did not work. If I remove $history->save();, it create new record ok. I think the save() method that built-in in Model provided by Laravel is problem. Can anyone tell me how to solve this.
I tried to build the raw query then executed it by DB:statement but it did not work too. Every try to execute anything with DB is failing.
Please research before re-inventing the wheel.
(Same stuff different sites in case one is down)
http://packalyst.com/packages/package/mpociot/versionable
https://packagist.org/packages/mpociot/versionable
https://github.com/mpociot/versionable
Cheers and good luck ;)

Resources