How to insert array fields data in Laravel5 - laravel-5

How can I insert multiple text fields data with Laravel.
I have two fields.
<input type="text" name="title[]" />
<input type="text" name="email[]" />
Now in controller I can get these values as below.
$name = $request->title;
$description = $request->email;
Here what i get when i print these values.
Array
(
[0] => title1
[1] => title2
)
Array
(
[0] => desc1
[1] => desc2
)
How can I add this with eloquent.

Method 1 :
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$objModel = new ModelName();
$objModel->name = $name[$i];
$objModel->description = $description[$i];
$objModel->save();
}
Method 2 :
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$data = array(
'name' => $name[$i],
'description' => $description[$i]
);
$insertData[] = $data;
}
ModelName::insert($insertData);

Related

Error updating data of 1 column by id in Codeigniter 3 database

I am posting the hosting order and I want to increase the "number of sales" column in my "hostings" table, but the data of all packages in my hostings table is increasing.
Here is my relevant code, I can say that there is no method I haven't tried.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
//FULL CODE
public function buy_hosting_post()
{
if ($this->input->post('package_id') && $this->session->userdata('id')) {
$hosting = $this->db->from('hostings')->where('id', $this->input->post('package_id'))->get()->row_array();
if ($hosting) {
$data = array(
'user_id' => $this->session->userdata('id'),
'domain' => $this->input->post('domain'),
'price' => $this->input->post('price'),
// 'end_date' => date('Y-m-d h:i:s',$end_date),
'package_id' => $hosting['id'],
'package_title' => $hosting['name'],
'payment_status' => 0,
);
$this->db->insert('hosting_orders', $data);
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
$hosting_order_successful = array(
'hosting_order_successful' => 'success',
);
$this->session->set_userdata('hosting_order_successful', $hosting_order_successful);
redirect(("hosting-siparisi-olusturuldu"));
} else {
redirect(base_url());
}
} else {
redirect(base_url());
}
}
I solved the problem in the following way, but it makes the system heavy.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->where('id', $this->input->post('package_id')); // added here.
$this->db->update('hostings', $data);

Validation can not updating value in database

I am uses validation for gst and adhar but when its error free i am updating value but value can not updating. I am giving updating code in else part. what is mistake done by me? need a solution. In if part i am checking validation and in else part if error is not coming, i am updating value from table but i can not work.
public function profile_update(Request $req,$id)
{
$mytime = Carbon::now();
$fullname = $req->input('fullname');
$email = $req->input('email');
$mobile = $req->input('mobile');
$gender = $req->input('gender');
$gstnumber = $req->input('gst_number');
$adharnumber = $req->input('aadhar_number');
$password = $req->input('password');
$cpassword = $req->input('c_password');
$updated_at = $mytime->toDateTimeString();
$created_at = $mytime->toDateTimeString();
$validator = Validator::make($req->all(), [
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
]);
if($validator->fails())
{
//dd("hello");
$messages = $validator->messages();
//return Redirect::to('/customer')->with('message', 'Register Failed');
return redirect('/profile')
->withErrors($validator)
->withInput();
}
else
{
if ($req->hasFile('update_image'))
{
$image = $req->file('update_image');
$filename = $image->getClientOriginalName();
$destinationPath = public_path('/images/users_profile/');
$image->move($destinationPath, $filename);
DB::update(
'update users set name = ?,email = ?,mobile = ?,image = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $filename, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
else
{
DB::update(
'update users set name = ?,email = ?,mobile = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
return redirect('/profile');
}
}
you dont need the if else statement
$req->validate([
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
// continue your update code here
]);
Simply do this and it will do the needfull for you
if your conditions are not met by the values it will return to the previous view and if the conditions are met, it will continue to run the codes.
for updating the data
$data = user::find(id);
$data->name = $name;
$data->email = $email;
.
.
.
.
//update all the fields
$data->save();

Upload multiple images from different input type files in laravel

I have 4 input type file with different name.How can i upload 4 images into the public folder and into 4 different column in database in same time?
$files=[];
if($request->hasfile('image_front_before')) $files[] = $request->file('image_front_before');
if($request->hasfile('image_back_before'))$files[] = $request->file('image_back_before');
if($request->hasfile('image_left_before'))$files[] = $request->file('image_left_before');
if($request->hasfile('image_right_before'))$files[] = $request->file('image_right_before');
if i dd(files); it will show below..It will appear the images that i have upload
array:4 [▼
0 => UploadedFile {#441 ▶}
1 => UploadedFile {#445 ▶}
2 => UploadedFile {#439 ▶}
3 => UploadedFile {#442 ▶}
]
I think the problem is here..
foreach ($files as $file)
{
if(!empty($file))
{
$filename= md5(time()).'.'.$file->getClientOriginalExtension();
$path = app(GlobalBookingController::class)- >getBookingImageDirectory();
$location = public_path($path.$filename);
Image::make($file)->save($location);
$data[]=$filename;
}
}
Below is the code to insert images into database
$vehicle_image =BookingVehicleImage::updateOrCreate(
[
'booking_id' => $id
],
[
'image_front_before' =>$data[0],
'image_back_before' =>$data[1],
'image_left_before' =>$data[2],
'image_right_before' =>$data[3]
]
);
if i upload 4 images in the same time only 2 will be upload into into public folder ..Sometimes for column image_left_before and image_right_before the images is correct..but for the column image_front_before will contain image_left_before and image_back_before will contain image_right_before..Sometimes only one column has right images and the other column has 3 same images even upload the different images at the start.
Try this example
public function store(Request $request)
{
$this->validate($request, [
'image1' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image2' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image3' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image4' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$article = new Article();
if ($request->hasFile('image1')) {
$image = $request->file('image1');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image1 = $name;
}
if ($request->hasFile('image2')) {
$image = $request->file('image1');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image2 = $name;
}
if ($request->hasFile('image3')) {
$image = $request->file('image3');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image3 = $name;
}
if ($request->hasFile('image4')) {
$image = $request->file('image');
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/articles');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$article->image4 = $name;
}
$article->title = $request->get('title');
$article->category_id = $request->get('category_id');
// $article->image = str_slug($request->get('image'));
$article->subtitle = $request->get('subtitle');
$article->description = $request->get('description');
$article->save();
return back()->with('success', 'Your article has been added successfully. Please wait for the admin to approve.');
}
This code is for saving multiple images to the particular path and to database
$i = 0;
foreach ($files as $file)
{
if(!empty($file))
{
$fileName = time().$i++.'.'.$file->getClientOriginalExtension();
Image::make($file)->save(public_path('/img/'.$fileName)); //This line will save your image to the particular path
array_push($files,$fileName);
$obj->image = $fileName;
$obj->save(); //save data to database
}
}

how to use php explode in laravel?

$user = $this->user;
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = $request['password'];
$user->save();
$name = explode(' ' ,$user->name);
$profile= $user->userdetail()->create([
'user_id' => $request->input('id'),
'first_name' => <the value of the first exploded string>
'last_name' => the value of the secondexploded string
]);
return redirect('confirmation');
}
how to split two words using explode function in php? For example i registered wth name of JOhn doe I want to create in my userdetail table the first_name of john and last_name of doe. How can i do it/
explode() returns an array of strings, so you can access elements by using keys:
$profile = $user->userdetail()->create([
'user_id' => $request->input('id'),
'first_name' => $name[0],
'last_name' => $name[1]
]);
You can use the following code
$full_name = "John Doe";
$name = explode(' ',$full_name);
$first_name = $name[0];
$last_name = $name[1];
Alternate way :
<?php
$ip = "fname lname";
$iparr = preg_split("/[\s,]+/",$ip);
echo "$iparr[0]";
echo "$iparr[1]";
?>
But explode is good(faster) than preg_split. ;)

CodeIgniter Captcha is not working

I am at my wits end and don't know why my code is not working . Everything seems good to me .. I have implemented a captcha in my user review function and added a verification method using callback_ .
The captcha is showing in the view and i have dumped the session data and the input field data and they are both working.
The form validation is also working in case of captcha input field but seems like the callback_check_captcha parameter is not working but the function seems fine to me .
Here is my controller
function user_review($id = null , $start = 0){
$check_id = $this->mdl_phone->get_phone_feature($id);
if ($check_id == null ) {
$data['phone_model'] = $this->get_phone_models();
$data['feature'] = null;
$data['title'] = 'Nothing Found';
$data['main_content']= 'phone/error';
echo Modules::run('templates/main',$data);
} else{
$data['phone_model'] = $this->get_phone_models();
$data['success'] = null;
$data['errors'] = null;
if($this->input->server("REQUEST_METHOD") === 'POST' ){
$this->load->library('form_validation');
$this->form_validation->set_rules('text','Review','required|xss_clean');
$this->form_validation->set_rules('captcha', 'Captcha','trim|required|callback_check_captcha');
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$data = array(
'phone_id' => $id,
'user_id' => $user_id,
'text' => strip_tags($this->input->post('text')),
);
$this->db->insert('user_review' ,$data);
$data['phone_model'] = $this->get_phone_models();
$data['success'] = 'Your Review has been successfully posted ';
$data['errors']= null;
}
}
// Initilize all Data at once by $id
$data['feature'] = $this->mdl_phone->get_phone_feature($id);
//$data['rating'] = $this->mdl_phone->get_user_rating($id);
$data['user_review'] = $this->mdl_phone->get_user_review($id , 5 , $start);
$this->load->library('pagination');
$config['base_url'] = base_url().'phone/user_review/'.$id;
$config['total_rows'] = $this->mdl_phone->get_user_review_count($id);
$config['per_page'] = 5;
$config['uri_segment'] = 4;
$config['anchor_class'] = 'class="page" ';
$this->pagination->initialize($config);
$this->load->helper('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'img_width' => 150,
'img_height' => 30,
);
$cap = create_captcha($vals);
$this->session->set_userdata('captcha',$cap['word']);
$data['captcha'] = $cap['image'];
$data['title'] = $this->mdl_phone->get_phone_title($id)." User Review , Rating and Popularity";
$data['main_content'] = 'phone/user_review';
echo Modules::run('templates/main',$data);
}
}
function check_captcha($cap)
{
if($this->session->userdata('captcha') == $cap )
{
return true;
}
else{
$this->form_validation->set_message('check_captcha', 'Security number does not match.');
return false;
}
}
The bellow CAPTHA working properly refer this code
$this->load->helper('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => base_url() . '/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$this->session->set_userdata($data);
$data['cap_img'] = $cap['image'];
I think your image url problem or you are not giving a file permission to the captha folder .

Resources