Form submission returns inputs Laravel - php

I'm trying to create a submission form, if a user submit the form it should redirect him to the next page which is in confirmation controller. So far it redirects back with the inputs like this
{"shipping_city":"gfg","shipping_phone":"087484","shipping_name":"Hellle",}
Here is my code
CheckoutController
public function store(Request $request)
{
foreach(session('cart') as $productId =>$item);
$product = product::find($productId);
//Insert into orders table
$order = Order::create([
'shipping_city' => $request->city,
'shipping_phone' => $request->phone,
'shipping_name' => $request->name,
]);
if ($order) {
foreach(session('cart') as $productId =>$item) {
if (empty($item)) {
continue;
}
$product = product::find($productId);
OrderProduct::create([
'order_id' => $order->id ?? null,
'product_id' => $productId,
'quantity' => $item['quantity'],
]);
}
return $order;
}
$cart = session()->remove('cart');
return redirect()->route('confirmation.index');
}
Checkout.blade
<form action="{{ route('checkout.store') }}" method="POST" id="payment-form">
{{ csrf_field() }}
<div class=shippingform>
<div class="form-group">
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{ auth()->user()->name }}" required>
</div>
<div class="half-form">
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" id="city" name="city" value="{{ old('city') }}" required>
</div>
</div> <!-- end half-form -->
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" class="form-control" id="phone" name="phone" value="{{ old('phone') }}" required>
</div>
<div class="spacer"></div>
<div class="spacer"></div>
<button type="submit" id="complete-order" class="buttons-primary full-width">Complete Order</button>
</form>
ConfirmationController
public function index()
{
{
if (! session()->has('success_message')) {
return redirect('/');
}
return view('thankyou');
}
}
Routes
Route::post('/checkout', 'CheckoutController#store')->name('checkout.store');
Any help will be appreciated.

Let's take a look at what your code currently does and what you want it to do:
Current Code with comments:
public function store(Request $request) {
foreach(session('cart') as $productId =>$item);
$product = product::find($productId);
//Insert into orders table
$order = Order::create([
'shipping_city' => $request->city,
'shipping_phone' => $request->phone,
'shipping_name' => $request->name,
]);
if ($order) { // If a new order was successfully created
foreach(session('cart') as $productId =>$item) {
// Do some stuff with each item / product
}
return $order; // return the newly created order with it's data
}
// If we didn't created a new order for whatever reason
$cart = session()->remove('cart');
return redirect()->route('confirmation.index'); // Redirect user to the "confirmation.index" route
}
As you can see, you just return the data of the created order (when $order is not false), otherwise you redirect to the "confirmation.index" page. Since this always does the opposite of what it should do (returning the order although you should be redirected to the confirmation page and vice versa), you have to swap the cases:
public function store(Request $request) {
...
if ($order) { // If a new order was successfully created
foreach(session('cart') as $productId =>$item) {
// Do some stuff with each item / product
}
$cart = session()->remove('cart');
return redirect()->route('confirmation.index'); // Redirect user to the "confirmation.index" route
}
// If we didn't created a new order for whatever reason
return false; // return something else, since we didn't create an order
}

Related

Is there a way to handle this error when updating a record in Laravel?

So this is my web.php
<?php
use App\Http\Controllers\BookingController;
use App\Http\Controllers\BookingRoomController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\GuestController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\RoomController;
use App\Models\Customer;
use App\Models\Room;
use App\Models\Guest;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome',[
'customerCount' => Customer::count(),
'guestCount' => Guest::count(),
'roomCount' => Room::count()
]);
});
// Customer Controller
Route::get('/customers',[CustomerController::class,'index'])->name('customers.index');
Route::get('/customers/add',[CustomerController::class,'create'])->name('customers.create');
Route::post('/customers',[CustomerController::class,'store'])->name('customers.store');
Route::post('/customers/update',[CustomerController::class,'update'])->name('customers.update');
Route::get('/customers/search',[CustomerController::class,'search'])->name('customers.search');
Route::get('/customers/{id}',[CustomerController::class,'show'])->name('customers.show');
Route::delete('/customers/{id}',[CustomerController::class,'destroy'])->name('customers.destroy');
// Guest Controller
Route::get('/guests',[GuestController::class,'index'])->name('guests.index');
Route::get('/guests/add',[GuestController::class,'create'])->name('guests.create');
Route::post('/guests',[GuestController::class,'store'])->name('guests.store');
Route::post('/guests/update',[GuestController::class,'update'])->name('guests.update');
Route::get('/guests/search',[GuestController::class,'search'])->name('guests.search');
Route::get('/guests/{id}',[GuestController::class,'show'])->name('guests.show');
Route::delete('/guests/{id}',[GuestController::class,'destroy'])->name('guests.destroy');
// Rooms
Route::get('/rooms',[RoomController::class,'index'])->name('rooms.index');
Route::post('/rooms/update',[RoomController::class,'update'])->name('rooms.update');
Route::get('/rooms/{id}',[RoomController::class,'show'])->name('rooms.show');
// Bookings
Route::get('/bookings',[BookingController::class,'index'])->name('bookings.index');
Route::get('/bookings/create',[BookingController::class,'create'])->name('bookings.create');
Route::post('/bookings',[BookingController::class,'store'])->name('bookings.store');
Route::get('/bookings/{id}',[BookingController::class,'show'])->name('bookings.show');
// Booking Rooms
Route::post('/bookingrooms',[BookingRoomController::class,'store'])->name('bookingrooms.store');
// Authentication
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
// Route::get('/email/verify', function () {
// return view('auth.verify-email');
// })->middleware('auth')->name('verification.notice');
// Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
// $request->fulfill();
// return redirect('/home');
// })->middleware(['auth', 'signed'])->name('verification.verify');
This is my customer controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Customer;
class CustomerController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['store','create']);
}
public function index(){
$customer = Customer::latest()->get();
return view('customers.index',['customer' => $customer]);
}
public function show($id){
$customer = Customer::findOrFail($id);
return view('customers.show',['customer' => $customer]);
}
public function create(){
return view('customers.create');
}
public function store(){
$customer = new Customer();
$customer->title = request('title');
$customer->first_name = request('firstname');
$customer->last_name = request('lastname');
$customer->date_of_birth = request('dateofbirth');
$customer->street = request('street');
$customer->town = request('town');
$customer->province = request('province');
$customer->postal_code = request('postalcode');
$customer->home_phone = request('homephone');
$customer->work_phone = request('workphone');
$customer->mobile_phone = request('mobilephone');
$customer->email = request('email');
$customer->save();
return redirect('/')->with('mssg','Added customer successfully!');
}
public function update(Request $req){
$customer = Customer::findorFail($req->id);
$customer->title = $req->title;
$customer->first_name = $req->firstname;
$customer->last_name = $req->lastname;
$customer->date_of_birth = $req->dateofbirth;
$customer->street = $req->street;
$customer->town = $req->town;
$customer->province = $req->province;
$customer->postal_code = $req->postalcode;
$customer->home_phone = $req->homephone;
$customer->work_phone = $req->workphone;
$customer->mobile_phone = $req->mobilephone;
$customer->email = $req->email;
$customer->save();
return redirect('/')->with('mssg','Updated customer successfully!');
}
public function search(Request $req){
$search = $req->get('search-customer');
$customer = Customer::where('first_name','like','%'.$search.'%')->paginate(5);
return view('customers.index',['customer' => $customer]);
// $records = ['first_name' => '%'.$search.'%',
// 'title' => '%'.$search.'%',
// 'last_name' => '%'.$search.'%'
// ];
}
public function destroy($id){
$customer = Customer::findOrFail($id);
$customer->delete();
return redirect('/')->with('mssg','Customer has been deleted!');
}
public function quantity(){
$customer = Customer::all();
return view('/',['customers' => $customer]);
}
}
This is my show.blade.php
#extends('layouts.app')
#section('content')
<div class="insert-customer-container-main">
<h1>Customer Information</h1>
<p>Please fill in the following</p>
<form class="insert-customer-container" action="{{ route('customers.update') }}" method="POST">
#csrf
{{-- get in controller to manipulate updating --}}
<input type="hidden" name="id" value="{{$customer->id}}">
<div class="customer-input-container row-one">
<div class="customer-input">
<label for="title">Title</label><br/>
<input style="width:945px" type="text" name="title" value="{{$customer->title}}" required>
</div>
</div>
<div class="customer-input-container row-two">
<div class="customer-input">
<label for="firstname">First Name</label><br/>
<input type="text" name="firstname" value="{{$customer->first_name}}">
</div>
<div class="customer-input">
<label for="lastname">Last Name</label><br/>
<input type="text" name="lastname" value="{{$customer->last_name}}">
</div>
<div class="customer-input">
<label for="dateofbirth">Date of Birth</label><br/>
<input type="date" name="dateofbirth" value="{{$customer->date_of_birth}}">
</div>
</div>
<div class="customer-input-container row-three">
<div class="customer-input">
<label for="street">Street</label><br/>
<input type="text" name="street" value="{{$customer->street}}">
</div>
<div class="customer-input">
<label for="town">Town</label><br/>
<input type="text" name="town" value="{{$customer->town}}">
</div>
<div class="customer-input">
<label for="province">Province</label><br/>
<input type="text" name="province" value="{{$customer->province}}">
</div>
</div>
<div class="customer-input-container row-four">
<div class="customer-input">
<label for="homephone">Home Phone</label><br/>
<input type="number" name="homephone" value="{{$customer->home_phone}}">
</div>
<div class="customer-input">
<label for="workphone">Work Phone</label><br/>
<input type="number" name="workphone" value="{{$customer->work_phone}}">
</div>
<div class="customer-input">
<label for="mobilephone">Mobile Phone</label><br/>
<input type="number" name="mobilephone" value="{{$customer->mobile_phone}}">
</div>
</div>
<div class="customer-input-container row-five">
<div class="customer-input">
<label for="postalcode">Postal Code</label><br/>
<input type="number" name="postalcode" value="{{$customer->postal_code}}">
</div>
<div class="customer-input">
<label for="email">Email Address</label><br/>
<input style="width:50vw;" type="email" name="email" value="{{$customer->email}}">
</div>
</div>
<input class="submit" type="submit" value="Update">
</form>
<form class="delete-form" action={{ route('customers.destroy', $customer->customer_id) }} method="POST">
#csrf
#method('DELETE')
<input type="submit" class="submit delete-btn" value="Delete">
</form>
</div>
#endsection
So my question is
When I'm editing a specific record and when I submit it, it redirects me to 404 page which is not what I'm expecting. Is there a way to fix this problem? I'm new in laravel and hoping someone could help. Thanks everyone!
May be your Route wrong
Route::get('/customers',[CustomerController::class,'index'])->name('customers.index');
Route::get('/customers/add',[CustomerController::class,'create'])->name('customers.create');
Route::post('/customers',[CustomerController::class,'store'])->name('customers.store');
Route::post('/customers/update',[CustomerController::class,'update'])->name('customers.update');
Route::get('/customers/search',[CustomerController::class,'search'])->name('customers.search');
Route::get('/customers/{id}',[CustomerController::class,'show'])->name('customers.show');
Route::delete('/customers/{id}',[CustomerController::class,'destroy'])->name('customers.destroy');
after
Route::resource('customers', 'CustomerController');
edit your all routes by resource after that try and also check your
route list
php artisan route:list
404: Not found
I think that is due to the wrong url you have passed as an action.
try to clean up your routes:
Route::group(['prefix' => 'customers', 'as' => 'customers.'], function() { Route::post('/update',[CustomerController::class,'update'])->name('customers.update'); });

Multi-step form in Laravel

I am trying to create a multi-step form for a user to fill after logging in. I created separate pages with forms that will be a part of the common form.
The data will be saved in the "users" table.
I am new to Laravel and I followed this: https://www.5balloons.info/multi-page-step-form-in-laravel-with-validation/
In my FormController I have these methods:
public function index(Request $request)
{
$request->session()->forget('user');
$user = User::all();
return view('form.index',compact('user',$user));
}
public function updateStep1(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step1',compact('user', $user));
}
public function postupdateStep1(Request $request)
{
$validatedData = $request->validate([
'first_name' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/update-step2');
}
public function updateStep2(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step2',compact('user', $user));
}
public function postupdateStep2(Request $request)
{
$validatedData = $request->validate([
'address' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/store');
}
public function store(Request $request)
{
$user = User::where('id',auth()->user()->id)->first();
$user = $request->session()->get('user');
$user->save();
return redirect('/form');
}
And these are the Routes:
Route::get('/form', 'FormController#index');
Route::get('/form/update-step1', 'FormController#updateStep1');
Route::post('/form/update-step1', 'FormController#postupdateStep1');
Route::get('/form/update-step2', 'FormController#updateStep2');
Route::post('/form/update-step2', 'FormController#postupdateStep2');
Route::post('/form/store', 'FormController#store');
This is the first part of the form:
#extends('layouts.app')
#section('content')
<h1>update - Step 1</h1>
<form action="/form/update-step1" method="post">
#csrf
<div class="form-group">
<label for="name">First Name</label>
<input type="text" value="{{ old('first_name', $user->first_name ?? null) }}" class="form-control" name="name">
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">Continue</button>
</form>
#endsection
I get an error when I try to submit, saying that the fields are required. So even if I do enter a name etc., it doesn't work. If I delete the validations, it seems like everything works but no data is added to the database.
Any suggestions?
You should use the input name is first_name because you have used first_name in the validation.
<input type="text" value="{{ old('first_name', $user->first_name ?? null) }}" class="form-control" name="first_name">
OR
If want to change name value in the user table:
FormController
$validatedData = $request->validate([
'name' => 'required',
]);
first part of the form:
<input type="text" value="{{ old('name', $user->name ?? null) }}" class="form-control" name="name">

form input cleared after submit data using laravel fram work

I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
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
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$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 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
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.

validate vat number is not working properly

I have a form for a user introduce some data, the vat number and country. When the user enter some data and click in "Go to step 2" is made an ajax request to the store() method and here should be be validated the vat number based on the selected country.
But its not working, the "dd($request->country);" shows null. Do you know why?
Html:
<form method="post" id="step1" action="">
...
<div class="form-group font-size-sm">
<select class="form-control" name="country" id="country">
#foreach($countries as $country)
<option value="">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group font-size-sm">
<label for="vat"
class="text-gray">VAT</label>
<input type="text" id="vat"
name="vat"
class="form-control" value="">
</div>
...
</form>
// store() method
public function store(Request $request, $id, $slug = null, Validator $validator){
...
$rules = [];
foreach ($request->question_required as $key => $value) {
$rule = 'string|max:255';
if ($value) {
$rule = 'required|' . $rule;
}
$rules["question.{$key}"] = $rule;
}
if ($all) {
$rules["name.*"] = 'required|max:255|string';
}
// the issue is here, country is null
dd($request->country);
dd(substr($request->country, 0, 2) . $request->vat);
//Validator::validate( substr($request->country, 0, 2).$request->vat); // false (checks format + existence)
$validator = Validator::make($request->all(), $rules, $messages);
$errors = $validator->errors();
$errors = json_decode($errors);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
return response()->json([
'success' => true,
'message' => 'success'
], 200);
}
// jQuery that do an ajax request
Try passing value into your tag . Php is not getting any value from your input so its showing null

codeigniter form not submitting data

I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.

Categories