retrieve value from session in laravel route - session

in route cats/create,I post a form with a validation.it will redirect to cats/create if don't accord with the regulation.I want to retrieve the $validation_result->messages() in action of cats/create.Will these be possible?the result of dd($message) is null:
Route::get('cats/create', function() {
$message=Session::get('message');
dd($message);
if($message->has('name')){
foreach ($message->get('name') as $messageone){
echo $messageone;
}
}
$cat = new Cat;
return View::make('cats.edit')
->with('cat', $cat)
->with('method', 'post');
});
Route::post('cats', function() {
$rules = array(
'name' => 'required|min:3', // Required, > 3 characters
'date_of_birth' => array('required', 'date') // Must be a date
);
$formresult=Input::all();
$validation_result = Validator::make($formresult,$rules);
if($validation_result->fails()){
return Redirect::back()->with('message', $validation_result->messages());
}else{
$cat = Cat::create($formresult);
$cat->user_id = Auth::user()->id;
if ($cat->save()) {
return Redirect::to('cats/' . $cat->id)
->with('message', 'Successfully created profile!');
} else {
return Redirect::back()
->with('error', 'Could not create profile');
}
}
});
but when I retrieve data from session in blade file,it is possible:
#if(Session::has('message'))
<div class="alert alert-success">
{{Session::get('message')}}
</div>
#endif
why? I cannot understand about this.

Change your condition from
if($validation_result->fails()){
return Redirect::back()->with('message', $validation_result->messages());
}
to
if($validation_result->fails())
{
$message = $validation_result->messages();
return Redirect::back()->with('message',$message);
}

maybe I saw wrong somethings,it work now!

Related

Uploading Multiple Image in Laravel and vue js

Am working on an app that should upload multiple images in the database using laravel and vue js.
Now for some reason it keeps on returning null value on the back end side. Hope someone can pin point the problem in this code.
this is my front-end code vue js
<template>
<div>
<div>
<form #submit.prevent="submit">
<input type="file" #change="onChange" multiple/>
<input type="submit" value="Upload">
</form>
</div>
</div>
</template>
<script>
export default {
data: ()=>({
image:[],
}),
methods:{
onChange(e){
this.image = e.target.files[0];
},
submit(){
let payload = new FormData();
for(let i=0; i<this.image.length; i++){
payload.append('image[]', this.image[i])
}
axios.post('/api/formsubmit',payload).then(res=>{
console.log("Response", res.data)
}).catch(err=>console.log(err))
}
},
}
</script>
and this is may back-end code Laravel 7
public function multipleupload(Request $request)
{
try{
if($request->hasFile('image')){
$upload = $request->file('image');
$file_name = time().'.'.$upload->getClientOriginalName();
$upload->move(public_path('image'), $file_name);
return response()->json([
'message'=>'File upload successfully!'
], 200);
}else {
return 'no data';
}
}catch(\Exception $e){
return response()->json([
'message'=>$e->getMessage()
]);
}
}
This code will always return 'no data'. been trying to figure it out but with no progress I hope someone can help.
Thanks,
if you want to upload multiple images you have to do loop, you can try this :
public function multipleupload(Request $request)
{
$input = $request->all();
request()->validate([
'image' => 'required',
]);
if($request->hasfile('image'))
{
foreach($request->file('image') as $image)
{
$imageName=file_name =$image->getClientOriginalName();
$image->move(public_path().'/images/', $imageName);
$insert['image'] = "$imageName";
}
}
Image::create($insert);
return back()
->with('success','Multiple Image Upload Successfully');
}

Laravel API - Display all districts when state field is empty

Below given is my code to display the specific districts of an inputted state. But in this code itself, i want to display all districts in the db if the state field is empty. How to modify my code to get such an output. So, my desired API works such that it returns all the districts when the api is called. And only if the state field is inputted, it shows the particular districts specific to it. Help me with ur suggestions.
public function state_lookup(Request $request)
{
$validator = Validator::make
($request->all(),
[
'state' => 'string',
]
);
if ($validator->fails()) {
return response()->json(
[$validator->errors()],
422
);
}
if(empty($request->state)){
$dist=PersonalDetails::get(['district']);
return response()->json($dist);
}
$data = PersonalDetails::where('state',$request->state)->get(['district']);
// dd($data);
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
else{
return response()->json(['message'=>'Invalid State']);
}
}
in failure case,I am getting json result as below
{
"message": "success",
"data": []
}
it shows "success" instead of "invalid state"
You can use when
$data = PersonalDetails::when(!empty($request->state),function ($query)use($request){
$query->where('state',$request->state);
})->get(['district']);
or
$data = PersonalDetails::where(function ($query)use($request){
if(isset($request)&&!empty($request)){
$query->where('state',$request->state);
}
})->get(['district']);
To avoid 0 key in response change like below
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
Try with this,
//In your controller
$request->validate([
'state' => 'string'
]);
// $request->validate it self return error messages you have to display
// for an example (write below code in your blade file)
#error('state')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
// write below code in your controller file
$details = PersonalDetails::select('district');
$details->where(function($query) use($request) {
if (isset($request->state) && $request->state != '') {
$query->where('state', $request->state);
}
// do what you want to filter in your query like above
});
$data = $details->get();

Problem with edit function using a modal Laravel

I have the next function
public function edit($id)
{
if(request()->ajax())
{
$data = Tbl_Perimetro::findOrFail($id);
return response()->json(['result' => $data]);
}
}
public function update(Request $request, Tbl_Perimetro $user)
{
$rules = array(
'rif' => 'required',
'razon_social' => 'required',
'holdings_id' => 'required',
'pines_id' => 'required'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
$form_data = array(
'rif' => $request->rif,
'razon_social' => $request->razon_social,
'holdings_id' => $request->holdings_id,
'pines_id' => $request->pines_id
);
Tbl_Perimetro::whereId($request->hidden_id)->update($form_data);
return response()->json(['success' => 'Datos actualizados satisfactoriamente.']);
}
My problem is that I would like to work with some models... and I know how to work with one model which is Tbl_Perimetro... I would like to work with another model called Tbl_Holding, But I'm using a modal to edit all this information.. here is the code of the modal:
$('#create_record').click(function(){
$('.modal-title').text('Add New Record');
$('#action_button').val('Add');
$('#action').val('Add');
$('#form_result').html('');
$('#formModal').modal('show');
});
$('#user_form').on('submit', function(event){
event.preventDefault();
var action_url = '';
if($('#action').val() == 'Add')
{
action_url = "{{ route('perimetro.store') }}";
}
if($('#action').val() == 'Editar')
{
action_url = "{{ route('perimetro.update') }}";
}
$.ajax({
url: action_url,
method:"POST",
data:$(this).serialize(),
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#user_form')[0].reset();
$('#user_perimetro').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
});
});
$(document).on('click', '.edit', function(){
var id = $(this).attr('id');
$('#form_result').html('');
$.ajax({
url :"/perimetro/"+id+"/edit",
dataType:"json",
success:function(data)
{
$('#rif').val(data.result.rif);
$('#razon_social').val(data.result.razon_social);
$('#holdings_id').val(data.result.holdings_id);
$('#pines_id').val(data.result.pines_id);
$('#carteras_id').val(data.result.carteras_id);
$('#hidden_id').val(id);
$('.modal-title').text('Editar Registro');
$('#action_button').val('Editar');
$('#action').val('Editar');
$('#formModal').modal('show');
}
})
});
This is the button to edit the information
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Editar</button>';
I would like to know is it exist a way to work with two models in the same modal... In this way I only can work with one model at the same time...
I think I got what you mean...
What you can do is using a route with 2 variables passed, the first variable could be the id of the tbl_perimetro and the 2nd variable could be the id of the tbl_holding.
So, this would fit like this:
public function edit($id, $idholding)
{
if(request()->ajax())
{
$data = Tbl_Perimetro::findOrFail($id);
$data1 = Tbl_Holding::findOrFail($idholding);
$alldata = array($data, $data1); //----->THIS WILL BREAK YOUR JSON STRUCTURE BE CAREFUL
return response()->json(['result' => $alldata]);
}
}
And the same in the update function:
public function update(Request $request, Tbl_Perimetro $user, Tbl_Holding $holding)
{
...
}
Be careful editing your routes, because starting in laravel 6 (I think) the variables HAVE to be literal, so the new routes have to match the variable name of the function p.ex:
Route::get('editmodels/{id}/{idholding}','Controller#edit'); //<----This will work
Route::get('editmodels/{id}/{id2}','Controller#edit'); //<----This won't work
Hope it helps!!

Yii2 Validate multiple models

I have two models in Yii2 (masterTransaction and splitTransaction), where each masterTransactions can have multiple splitTransactions. Each splitTransaction has an attribute 'amount'. My problem is I need to validate if the sum over all 'amount' attributes is 0.
My first solution was to make another model called Transaction, in which I had an attribute where I saved an instance of the masterTransaction model and another attribute with an array of splitTransaction instances. I did the validation with a custom inline validatior, which work perfectly.
Transaction model
class Transaction extends Model
{
public $masterTransaction;
public $splitTransactions;
public function init()
{
$this->masterTransaction = new MasterTransaction();
$this->splitTransactions[] = new SplitTransaction();
}
public function rules()
{
return [
['splitTransactions', 'validateSplitTransactions'],
];
}
public function validateSplitTransactions($attribute, $params)
{
$sum = 0;
foreach ($this->$attribute as $transaction) {
$sum = bcadd($sum, $transaction->amount, 3);
}
if ($sum != 0) {
$this->addError($attribute, 'The sum of the entries has to be 0');
}
}
public function save()
{
$this->masterTransaction->save();
foreach ($this->splitTransactions as $splitTransaction) {
$splitTransaction->master_transaction_id = $this->masterTransaction->id;
$splitTransaction->save();
}
}
}
Controller function to create the model
public function actionCreate()
{
$transaction = new Transaction();
$count = count(Yii::$app->request->post('SplitTransaction', []));
for ($i = 1; $i < $count; $i++) {
$transaction->splitTransactions[] = new SplitTransaction();
}
if ($transaction->masterTransaction->load(Yii::$app->request->post()) && Model::loadMultiple($transaction->splitTransactions, Yii::$app->request->post())) {
$transaction->masterTransaction->user_id = Yii::$app->user->id;
foreach ($transaction->splitTransactions as $splitTransaction) {
$splitTransaction->user_id = Yii::$app->user->id;
}
if ($transaction->validate()) {
$transaction->save();
}
}
return $this->render('create', [
'transaction' => $transaction,
]);
}
But when I tried building a form to input the data, I ran into a problem with the Ajax validation. The validation would work, but Yii didn't know where to put the error message, so it just deleted it.
I suspect that this is just not the preferred way in Yii2 model my data, but I don't really have another idea. Maybe someone has some ideas for me.
Option 1.
It depends on your view file codes. Does your form contains "splitTransactions" variable? If not, you can put it like this
<?= $form->field($model, 'splitTransactions')->hiddenInput(['maxlength' => true])->label(false); ?>
The variable will be hidden, but still show errors. In some case validation will not be fired because of empty value of "splitTransactions" variable.
"splitTransactions" should contain some value to fire validation. You can put some value to if before pasting the form like this
$model->splitTransactions=1;
Option 2.
You can add error to other variable (which form contains) like this
public function validateSplitTransactions($attribute, $params)
{
$sum = 0;
foreach ($this->$attribute as $transaction) {
$sum = bcadd($sum, $transaction->amount, 3);
}
if ($sum != 0) {
$this->addError('transaction_number', 'The sum of the entries has to be 0');
}
}
Look, form should contain "transaction_number" variable. Error will be added to "transaction_number" input.
Option 3. In my experience.
It is better to separate ajax validation from form action url a.g. create another controller action for ajax validation and use it.
Example
Create model FeedbackForm
class FeedbackForm extends Model
{
public $name;
public $email;
public $text;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['name', 'email', 'text'], 'required'],
[['name', 'email'], 'string', 'max' => 128],
[['email'], 'email'],
[['text'], 'string', 'max' => 512],
];
}
public function attributeLabels()
{
return [
'name' => \Yii::t('front', 'Name'),
'email' => \Yii::t('front', 'Email'),
'text' => \Yii::t('front', 'Message text'),
];
}
}
put actions to SiteSontroller
public function actionFeedback()
{
$model= new \frontend\models\FeedbackForm;
$model->load(Yii::$app->request->post());
if($model->validate()) {
$newFeed=new \frontend\models\Feedback;
$newFeed->create_time=new \yii\db\Expression('NOW()');
$newFeed->name=$model->name;
$newFeed->email=$model->email;
$newFeed->is_new=1;
$newFeed->text=$model->text;
if($newFeed->save()) {
\Yii::$app->session->setFlash('success', \Yii::t('front', 'Your message has accepted'));
} else {
\Yii::$app->session->setFlash('error', \Yii::t('front', 'Error on save'));
}
} else {
\Yii::$app->session->setFlash('error', \Yii::t('front', 'Data error'));
}
return $this->redirect(['/site/index']);
}
public function actionFeedbackvalidate()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model= new \frontend\models\FeedbackForm;
$model->load(Yii::$app->request->post());
return ActiveForm::validate($model);
}
And create form inside view
<?php $model=new \frontend\models\FeedbackForm; ?>
<?php $form = ActiveForm::begin([
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validationUrl'=>['/site/feedbackvalidate'],
'validateOnSubmit' => true,
'id' => 'form-feedback',
'action'=>['/site/feedback'],
'options'=>['class'=>'some class', 'autocomplete'=>'off']
]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('name'), 'autocomplete'=>'off'])->label(false); ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('email'), 'autocomplete'=>'off'])->label(false); ?>
<?= $form->field($model, 'text')->textarea(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('text'), 'autocomplete'=>'off'])->label(false); ?>
<div class="form-group">
<input type="submit" class="btn btn-default" value="<?php echo Yii::t('front', 'Send') ?>">
</div>
<?php ActiveForm::end(); ?>
That is it

Restriction for not allowing same email and password in the database for my signup form

i want to make a restriction in my signup form which the user cant signup with the already exists email and password..
in my controller:
i already make a rules or callback
array(
'field' => 'txt_email',
'label' => 'Email',
'rules' => 'required|valid_email|callback_check_if_valid_email|trim',
),
check_if_valid:
public function check_if_valid_email()
{
$where = array('email' =>$this->input->post('txt_email'),'password' =>$this->input->post('txt_password'));
$this->load->model('database_model');
if ($user = $this->database_model->validate_user('user', $where))
{
foreach ($user as $row) {
$checkemail = $row->email;
$checkpassword = $row->password;
}
if ($checkemail == $this->input->post('txt_email')){
$this->form_validation->set_message('check_if_valid_email', 'Email already existed!');
return false;
}
else
{
if ($checkpassword = $this->input->post('txt_password'))
{
$this->form_validation->set_message('check_if_valid_email', 'Email already exists!');
return false;
}
else
{
return true;
}
}
}
}
in my model:
public function validate_user($table, $where)
{
$this->db->where($where);
$query = $this->db->get($table);
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
CodeIgniter's Form Validation library comes with the rule you're looking for, called: is_unique
http://www.codeigniter.com/userguide3/libraries/form_validation.html#rule-reference
Your validation rules will look like this;
required|valid_email|is_unique[users.email]|trim
All you have to set it the table and column you want to be unique (users.email).
Hope this helps.

Resources