Laravel: How to pass radio button value to controller and update? - php

I want to update customer order status at admin panel. How to pass the radio button value to the controller using form.
Blade file
<form action="{{url('vendor/orderstatus-update/' .$order->id)}}" method="POST" >
{{ csrf_field() }}
<div class="card-body">
<h4 class="card-title">Order Status</h4>
<div class="form-group">
<div class="col-md-6">
<input type="radio" name="order_status" id="Pending" value="Pending" > Pending<br>
<input type="radio" name="order_status" id="Processing" value="Processing" > Processing<br>
<input type="radio" name="order_status" id="Delivery" value="Delivery" > Out For Delivery<br>
<input type="radio" name="order_status" id="Cancelled" value="Cancelled" > Cancelled<br>
</div>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Below code is the function I write in controller
public function updateOrderStatus(Request $request,$orderId){
$orders=Order::where('order_id',$orderId)->find();
$orders->update(['order_status'=>$request['order_status']]);
return response()->json(['status'=>true],200);
}
order table
The error that I get is:
{"success":false,"message":"A non well formed numeric value encountered"}
Any solution to fix this?

You can try like this.
public function updateOrderStatus(Request $request,$orderId)
{
try
{
$inputs = $request->all();
$orders = Order::where('order_id', $orderId)->find();
$orders->update(['order_status' => $inputs['order_status']]);
return response()->json(['status' => true], 200);
} catch (\Throwable $th) { dd($th->__toString()); }
}

Related

Laravel 8, how to upload more than one image at a time

I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}

how to redirect and show error validateion in laravel

good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist

Laravel 5.4 How to fix 'No query results for model'

Whenever I try to access /skills/add through an anchor in another page I get this error
The anchor that redirects to this page(with GET method) is:
<a class="btn icon-btn btn-success" href="/skills/add">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
Tried using dd("test") to test it out but won't even work.
This are my routes for skills/add this:
Route::put('/skills/add', 'SkillsController#add');
Route::get('/skills/add', 'SkillsController#addIndex');
Here are my functions in SkillsController
public function addIndex() {
if (Auth::check()) {
return view('skills.add');
} else {
return redirect('/home');
}
}
public function add(Request $request) {
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
$validator = Validator::validate($request->all(), $skillRules);
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
the skills.add view is this
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="/skills/add">
{{method_field('PUT')}}
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input name="name" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Not sure what happened, if someone in the future has this same problem, I literally just deleted and made manually thee controller, model and blade and it started to work. Not a lot of science or explain, sorry for that.
Change your route to named ones
Route::GET('/skills/add', 'SkillsController#addIndex')->name('addSkills');
Route::POST('/skills/add', 'SkillsController#add')->name('saveSkills');
and your blade to
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="{{route('saveSkills')"> //** Change this
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input type="text" name="name" class="form-control"> //** Change this
</div>
</div>
//Remaining form groups
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Change your anchor tag's href value to named route like
<a class="btn icon-btn btn-success" href="{{route('addSkills')}}">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
and your controller
// SHOW ADD NEW SKILL FORM
public function addIndex() {
if (Auth::check()) {
return view('skills.add'); //view path is skills->add.blade.php
} else {
return redirect('/home');
}
}
//SAVE ADD NEW SKILL FORM DATA
public function add(Request $request) {
dd($request->name); //Check if value is getting
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
$validator = Validator::validate($request->all(), $skillRules);
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
also add use App\RampUp\Skills; on top of controller
Sorry but there is no POST-route for <form method="POST" action="/skills/add">
maybe the POST is still executed.
On the other hand most Route errors could be resolved by clearing the cache (if present), rearranging the routes or put a group in between like
Route::group(['prefix' => 'skills'], function() {
Route::put('/add', 'SkillsController#add');
Route::get('/add', 'SkillsController#addIndex');
}

How to pass default values from codeigniter application to different website

Error
Not able to pass the value from this application to other website.
View
In this view using action i have called the controller function. If the user selects Pay-Me then value 1 will be passed to controller function.
<form id="formMuktinath" method="post" action="<?php echo base_url().'index.php/booking/bookManakamana'?>">
<div class="form-group">
<label for="name" class="col-sm-3 col-lg-offset-2 control-label">Payment From </label>
<div class="col-sm-4">
<select class="select form-control" name="manakamana[payment_from]">
<option value="1" selected>Pay-Me</option>
<option value="2">BIL</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
Controller
If 1 is selected then it calls payme website. Then there redirect function using $data does not pass amt value to payme website.
public function bookManakamana(){
if ($data = $this->input->post('manakamana')) {
$data['created_on'] = date('Y-m-d H:i:s');
if ($data['payment_from'] == '1') {
$data['amt'] = '100';
redirect('http://dev.payme.com/pay/main',$data);
}
if ($data['payment_from'] == '2') {
echo 'bli';
exit;
}
redirect('booking/index');
} else {
$this->load->view('index');
}
}
if you want to pass values in link as get variable
www.somewebsite.com/?var='value'
but if you want to send variable as post you need to use curl

how to fix preg_replace():Parameter mismatch, pattern is a string while replacement is an array

I am getting the check box values(multiple values) from view where user select the topics they are interested and store multiple values in a column in my database. So used serialize() to store them in my database. When i try to do that. It throws me the above mentioned error. I went through previous questions in Stackoverflow and did few changes like
$data = array(
'topics' => $post['topics'] ,);
to
$data = [
'topics' => $post['topics'] ,];
Again it shows the same error , Here is my View
<div class="panel-body">
<center><h2> Select the topic you are interested in</h2></center><br>
<form enctype="multipart/formdata"class="form-horizontal" role="form" method="POST" action="{{ url('/topicStore') }}">
{{ csrf_field() }}
<center>
<input type="checkbox" name="topics[]" value="sports"> Sports</input>
<input type="checkbox" name="topics[]" value="education"> Education</input>
<input type="checkbox" name="topics[]" value="family"> Family</input>
<input type="checkbox" name="topics[]" value="friends"> Friends</input></center><br>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i>Add topics
</button>
</div>
</div>
</div>
Here is my controller.
public function storeSelection(Request $request)
{
$post = $request->all();
$val=\Validator::make($request->all(),
[
'topics' => 'required',
]);
if ($val ->fails())
{
return redirect()->back()->withErrors($val->errors());
}
else
{
$data = array(
'topics' => $post['topics'] ,
);
$topics = serialize($data);
$updatedata = DB::table('users')->where('name',\Auth::user()->name)
->update($data);
if ($updatedata>0) {
return redirect('home');
}
}
}
I want to save the array of data which i get from the view to a column in database. I have used serialize(). Are there any other better ways to do this ?

Categories