Inserting a JSON array from Laravel - php

I'm wondering how I can loop insert an array value to database through Laravel.
A sample of a Json is here:
[{"rid":"252","recipient_id":"1","email_type":"Body","to_cc_bcc":"to","start_dte":"2016-05-18","end_dte":""},{"rid":"252","recipient_id":"5","email_type":"Body","to_cc_bcc":"to","start_dte":"2016-05-18","end_dte":""}]
And my controller for storing such is this:
public function store()
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'name' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('reports')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
//Dump Recipient array
$cleanRecipients = json_decode(Input::get('test'), true);
foreach($cleanRecipients AS $value)
{
$report_recipient = new ReportRecipients;
$report_recipient->recipient_id = $value['recipient_id'];
$report_recipient->rid = $value['rid'];
$report_recipient->email_type = $value['email_type'];
$report_recipient->to_cc_bcc = $value['to_cc_bcc'];
$report_recipient->start_dte = !empty($value['start_dte']) ? $value['start_dte'] : null;
$report_recipient->end_dte = !empty($value['end_dte']) ? $value['end_dte'] : null;
}
$report_recipient->save();
// redirect
Session::flash('message', 'Report was Successfully Saved!');
return Redirect::to('reports');
What happens is that, it only stores the last set of values into the table and not all of them. I appreciate any help and thanks in advance.

Put your save() inside your loop. Also, you should do it in one transaction, to be atomic.
\DB::transaction(function() use($cleanRecipients) {
foreach($cleanRecipients AS $value) {
$report_recipient = new ReportRecipients;
$report_recipient->recipient_id = $value['recipient_id'];
$report_recipient->rid = $value['rid'];
$report_recipient->email_type = $value['email_type'];
$report_recipient->to_cc_bcc = $value['to_cc_bcc'];
$report_recipient->start_dte = !empty($value['start_dte']) ? $value['start_dte'] : null;
$report_recipient->end_dte = !empty($value['end_dte']) ? $value['end_dte'] : null;
$report_recipient->save();
});

You need to put $report_recipient->save(); inside your foreach loop.

Related

validate and saving an array of objects laravel 6, vue, axios

vue function:
sendData() {
this.isLoading = true;
const postData = {
data: this.items,
};
var self = this;
axios.post(this.postUrl, postData).then(function (response) {
console.log(response.data);
self.isLoading = false;
});
this.items = [];
},
Laravel controller:
public function store(request $request)
{
foreach ($request->data as $data) {
$serie = [];
$serie = ['imei' => $data['serie']];
$imei = new Imei([
'imei' => $data['serie'],
'status_id' => 1,
'sucursal_id' => $data['sucursal'],
'equipo_id' => $data['equipo']
]);
$validator = Validator::make($serie, [
'imei' => 'unique:imeis,imei|digits:15',
]);
if ($validator->fails()) {
// Here I need to build the response of every imei with its validation error
} else {
$imei->save();
}
}
return >Here I want to return the errors back to vue
}
my vue app sends to laravel trough axios an array of objects that looks like this [{imei:xxxx,sucursal_id...},{imei:xxxx,sucursal_id...}] I need to validate imei is unique and save it, and if error return errors in the same way [{imei:xxxx,errorMsg: 'already exist in DB'}]. but I can't find the proper way to do it.
Basically you want to customize your errorbag right ? try this one out. Add this inside your fail condition. Let me know if it works.
$err = [{imei:xxxx,errorMsg: 'already exist in DB'}];
foreach ($validator->errors()->toArray() as $error) {
foreach($error as $sub_error) {
array_push($err, $sub_error);
}
}
return ['errors'=>$err];

how to check if data already exist when insert data

I want to ask how to to check the data if we input data if there is the same data that cannot be inserted.
My code:
$obj = new Pengajuan();
// $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
$status = "Tersmpan";
} else {
$status = "Gagal";
}
echo json_encode(array("status" => $status));
Above of the code add a validation like below:
$this->validate([
'id_nasabah' =>'unique:pengajuans'
]) ;
And then rest of your controller code.
try this:
public function store(Request $request)
{
$this->validate($request,[
'id_nasabah'=>'required|exists:your_table_name,id',
'tgl_pengajuan'=>'more_validations',
'besar_pinjaman'=>'more_validations',
]);
//if $this->validate() fails, it will return a response 422 code error
//else it will continue with the creation of your object
//is a good idea to use a try-catch in case of something goes wrong
try
{
$pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));
return response->json([
'pengajuan'=>$pengajuan,
'status'=>'Tersmpan',
],200);//return a http code 200 ok
}
catch(Exception $e)
{
//'message'=>'this will return what is the error and line'
return response()->json([
'message'=>$e->getMessage().'/'.$e->getLine(),
'status'=>'Gagal',
],422);
}
}

Yii2; code running in "else" block first, and then running code before "if" block?

I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.

custom validation phalcon without library

I'm beginner in PHP and phalcon, I want to use custom validation and creating default value.
My controller is:
use Phalcon\Mvc\Controller;
class OspoController extends Controller
{
public function indexAction()
{
}
public function createAction()
{
$ospo = new Ospos();
// Store and check for errors
$success = $ospo->save(
$this->request->getPost(),
array('isEmailConfirmed', 'email', 'password', 'salt' ,'phoneNum', 'verifiedPhoneStatus', 'languageId', 'firstName', 'lastName', 'address', 'cityId', 'provId', 'countryId', 'postCode')
);
$data = array();
if ($success) {
$data[] = array(
'status' => 'success'
);
echo json_encode($data);
} else {
foreach ($ospo->getMessages() as $message) {
$msg = $message->getMessage();
$data[] = array(
'message' => $msg
);
}
echo json_encode($data);
}
$this->view->disable();
}
I want if isEmailConfirmed is null - I want to create value that isEmailConfirmed = 0;
How to change array value of getPost()?
(can I do this) Should i change the code with
$isEmailConfirmed = $_POST['isEmailConfirmed'];
and
$ospo->save($isEmailConfirmed, $etc, $etc)?
Thank you.
First of all, you can just store POST data in a variable. Then just check for null and assign default value if needed before saving.
$data = $this->request->getPost();
if (!isset($data['isEmailConfirmed']) {
$data['isEmailConfirmed'] = 0;
}
Another way is to save null value, but in that case you should set up DEFAULT for that column in your database table.

adding multiple entry in laravel

Below code works adding single single entry i want to store multiple parent_id and user_id
public function test($p_id, $pl_id)
{
$CheckRelationship = UsersRelationship::where('parent_user_id', $p_id )->where('child_user_id', $pl_id )->first();
if( $CheckRelationship )
{
return Response::json( [
'ok'=> false,
'message'=> 'The profiles are currently linked '
] ,422);
}
$user = User::find( $pl_id );
$user->p_id = $p_id;
$user->updated_by = $p_id;
//$user->status = 1;
$user->save();
$UsersRelationship = new UsersRelationship;
$UsersRelationship->parent_user_id = $parent_id;
$UsersRelationship->child_user_id = $player_id;
$UsersRelationship->save();
return Response::json( [
'ok'=> true,
'message'=> 'Linked',
] ,200);
}
I want to pass multiple value
$UsersRelationship = new UsersRelationship;
$UsersRelationship->parent_user_id = $parent_id; //single value passing
$UsersRelationship->child_user_id = $player_id; //single value passing
$UsersRelationship->save();
foreach($UsersRelationship as $k=>$values){
$UsersRelationship['parent_user_id'] = $values;
$UsersRelationship['child_user_id'] = $values;
$UsersRelationship->save();
}
doesn't work for me please suggest where i am mistaking early reply highly appreciated thanks in advance
Parameters in URLs will work only for a singular user relationship. If you wish to pass multiple relationships, JSON is your friend.
JSON Sample:
[
{
'parent_user_id': 1,
'child_user_id': 2,
},
{
'parent_user_id': 2,
'child_user_id': 2,
}
]
PHP controller function:
public function test(\Illuminate\Http\Request $request) {
//Pass your information through a GET parameter or POST it through a form
// 'user_relationship' is the name of the field, expecting data in JSON format
$user_relationships = json_decode($request->get('user_relationship'));
//array to store all relationships that were not linked
$relationshipsNotLinked= [];
//Loop through each relationship, attach where possible
foreach($user_relationships as $user_relationship_row) {
$CheckRelationship = UsersRelationship::where('parent_user_id', $user_relationship_row['parent_user_id'] )->where('child_user_id', $user_relationship_row['child_user_id'] )->first();
//If exists, we don't save.
if( $CheckRelationship ) {
$relationshipsNotLinked[] = $user_relationship_row['child_user_id'];
} else {
//Else we link relationship
//Not sure what the links below does..
//users cannot have `p_id` attribute, given that they may have multiple parents. Same goes for 'updated_by' attribute
$user = User::find( $user_relationship_row['parent_user_id'] );
$user->updated_by = $user_relationship_row['parent_user_id'];
//$user->status = 1;
$user->save();
//Save relationship
$UsersRelationship = new UsersRelationship();
$UsersRelationship->parent_user_id = $user_relationship_row['parent_user_id'];
$UsersRelationship->child_user_id = $user_relationship_row['child_user_id'];
$UsersRelationship->save();
}
}
if(count($relationshipsNotlinked)) {
//Some relationships were not linked, we display an error message
return Response::json( [
'ok'=> false,
'message'=> 'The following profiles are already linked: '.implode(',',relationshipsNotLinked),
] ,422);
} else {
//Display success message
return Response::json( [
'ok'=> true,
'message'=> 'Linked',
] ,200);
}
}

Categories