Pass form data through url by setting in route - php

I have set a route in my Laravel project, if it was with href I would have done it like this {{route('destination'),$country_from,$country_to}} but now I want to pass in the form data as the $country_from and $country_to please how can I do this
<form action="{{route('destination')}}">
#csrf
<input type="text"
class="search-form flexdatalist"
name="origin"
placeholder="country_from"
data-search-in='name'
data-min-length='1'
/>
<img src="{{URL::asset('img/location.svg')}}" class="search-icon origin" width="28px" height="21px"/>
</div>
<div class=" col-md-3 mx-0 px-0">
<input type="text"
class="search-form flexdatalist"
name="country_to"
data-search-in='name'
data-min-length='1'
placeholder="Travelling to"
/>
<img src="{{URL::asset('img/location.svg')}}" class="search-icon destination" width="28px" height="21px"/>
</div>
<div class="col-md-3 mx-0 px-0">
<input type="text"
class="search-form flexdatalist"
name="residence"
data-search-in='name'
data-min-length='1'
placeholder="Residing In"
/>
<img src="{{URL::asset('img/location.svg')}}" class="search-icon residence" width="28px" height="21px"/>
</div>
<div class="col-md-3 px-0">
<input type="submit" value="Search Visas" class="btn btn-primary search-btn"/>
</form>
Route
Route::get('/{country_from}/{country_to}', 'DestinationCountriesController#index')->name('destination');

I don't understand exactly what you want to do:
You want to redirect the user to the URL after form submit, and use form values in the redirection URL?
In your form POST controller, retrieve inputs from $request and return a return redirect()->route('route_name', ['country_from' => $request->country_from, 'country_to' => $request->country_to])
You want to use URL values as input values, so on page load, inputs are filled with URL values?
Your "destination" route controller method accepts as parameter $country_from and $country_to as you declared those variables with your route. You so have those variables in your controller, you can sanitize them, bind them to the returned view (eg: return view('view', $data) or return view('view', compact('country_from', 'country_to'))), and accessed it as usual in your blade.
You can also access URL values using \Request::route('country_from'). You should sanitize this values before using it as input.
use those variables in your blade as input value attributes, or placeholder, anywhere {{$country_to}}.

Related

How to pass and catch variable when the method is POST then the route is GET?

I'm developing a web application, and I want to pass variable called ID when the form method is post that linked to open other form but in the config/routes I'm using $routes[page_A][get] = 'Controller' not $routes[page_A][post] = 'Controller'.
I'm using Codeigniter framework here, I've tried to change the controller with $this->input->get('id') but it doesn't work and I don't have any idea whats really happen in my codes.
The Sender Form View code
<form action="<?= base_url().'progres_save'; ?>" method="POST">
<div class="form-group">
<div class="form-row">
<label for="idJobOrder">ID Job Order</label>
<input type="text" name="idJobOrder" class="form-control" value="<?php echo $rd[0]->kodejobglobal; ?>" readonly>
</div>
</div>
<div class="form-group">
<div class="form-row">
<a class="btn btn-primary col-xl-1 col-sm-1 mb-1 ml-auto mr-0 mr-md-2 my-0 my-md-3" href="job" id="back" role="button"><i class="fas fa-fw fa-arrow-left"></i> Back</a>
<button class="btn btn-primary btn-block col-xl-1 col-sm-1 mb-1 mr-0 mr-md-2 my-0 my-md-3">Save <i class="fa fa-fw fa-arrow-right"></i></button>
<input type="hidden" name="id" value="<?php echo $rd[0]->kodejobspesifik ?>">
</div>
</div>
</form>
The Sender Form Controller code
public function save()
{
$idglobal = $this->input->post('idJobOrder');
$data = array('jobnya' => $idglobal );
$this->Model_joborder->save_pg($data,'lapharian');
redirect('progres_material');
}
The Config Routes code
$route['progres_save']['get']='error';
$route['progres_save']['post']='save';
$route['progres_material']['get']='matused';
$route['progres_material']['post']='error';
The Recipient Form Controller code
public function matused()
{
$id = $this->input->get('id');
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
The Recipient Form View code
<form method="POST" action="<?= base_url().'matsave'; ?>">
<div class="form-group">
<div class="form-row">
<?php if (isset($rd[0])) {?>
<input type="hidden" value="<?php echo $rd[0]->jobspesifiknya; ?>" name="idClient" class="form-control" placeholder="First name" readonly>
<?php } ?>
</div>
</div>
</form>
What I expect is the input id value from Sender will be passed and catch on Recipient form as input idClient. Can anyone her help me to find out the solution? Thank you.
You can use PHP global variable $_REQUEST to capture the data if you are not sure about the request type like this,
public function matused()
{
$id = $_REQUEST['id'];
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
You forgot to include the id data on the redirect after the save() method is called, so you will not get anything by calling $this->input->get('id').
To solve this, pass the id data along with the redirect :
redirect('progres_material?id=' . $this->input->post('id'));
But that of course it will gives you an extra parameter on the url. If you don't want additional parameter, you could alternatively use session to pass id data while redirecting, on CodeIgniter there is a method called set_flashdata to do this :
$this->session->set_flashdata('id', $this->input->post('id'));
redirect('progres_material');
And to get the id session data on the matused() method, use the following code :
$id = !empty($this->session->flashdata('id')) ? $this->session->flashdata('id') : $this->input->get('id');

Laravel form submission with url parameters

When the user accesses a certain brand page, I pull the information associated with that brand. Then the user has the chance to submit an application for this brand.
When the user submits the form, I want the form to post to /apply/brand/{brand_id} because I want to store this application in my application table with the brand_id as one of the fields (the other fields in this table comes from the fields in my form, but the brand_id will be an URL parameter)
The problem is that when I submit the form, the form posts to /apply/brand/undefined and the submission does not work correctly. I do not reach the ApplicationController#apply_store method.
EDIT:
To debug my problem, I printed out the {{$brand -> id }} right before the element and it printed out fine. However, when the form submits, it goes to /apply/brand/undefined instead of /apply/brand/{{$brand -> id }}. The $brand variable somehow becomes undefined inside of my form.
EDIT:
I hardcoded the from to submit to /apply/brand/43. When I press submit, the url shows up as /apply/brand/43 at first but then quickly changes to /apply/brand/undefined before redirecting me to my default page.
Controller Method for Accessing a Brand Page
public function brandProfile(){
$brand = Brand::where('user_id', Auth::user()->id)->first();
$industry = Industry::where('status', 1)->get();
return view('new-design.pages.profile_brand')
->withData($brand)
->withIndustry($industry);
}
Brand Application Form
<form id="application_form" method="post" action="/apply/brand/{{ $data -> id }}" enctype="multipart/form-data">
{{ csrf_field() }}
<ul>
<div class="col-md-6">
<li>
<label>First Name</label>
<input type="text" class="form-control" name="firstname" placeholder="First Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Email</label>
<input type="email" class="form-control" name="email" placeholder="Email"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Instagram Handle</label>
<input type="text" class="form-control" name="instagram" placeholder="Instagram Handle"/>
</li>
</div>
<li>
<label>Cover Letter</label>
<p>Please write your message in the space below, or attach a file (-list of file types accepted-)</p>
<textarea cols="30" rows="50" name="message" class="textarea"></textarea>
</li>
<li>
<div class="upload-cover-letter">
<i class="fa fa-paperclip" style="cursor:pointer;font-size:20px;"></i>
<input type="file" name="file" id="myFileDocument" class="inputfile inputfile-1"/>
<label for="myFileDocument" id="myFileDoc"><span>Choose File</span></label>
<span style="font-size: 12px">No File Chosen</span>
<span class='hidden_text' style="font-size: 12px">Upload File (Max 2MB)</span>
</div>
<input type="hidden" id="myFileName" name="file_name" />
</li>
</ul>
<div class="btn-center">
<button type="button" class="btn btn-gradient waves-effect" id="create_campaign">Apply Now</button>
</div>
</form>
Route in web.php
Route::post('/apply/brand/{brand_id}', 'ApplicationController#apply_store');
Store application in database
public function apply_store(Request $request)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $request->get('brand_id'),
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// TODO: add helper message to confirm application did return
return redirect('/apply');
}
In your controoler metohd apply_store, you need to put the variable that will receive the variable sended by url parameter.
public function apply_store(Request $request, $brand_id){}
I typically work with compact or with to send the param to the blade view. So:
return view('new-design.pages.profile_brand', compact('brand'));
or without compact:
return view('new-design.pages.profile_brand')->with('brand', $brand)
I haven't seen the withVar that you are attempting above (doesn't mean it doesn't exist though). Try with compact and dump $brand on the view to make sure its coming through with data (not undefined). If that dumps successfully, but still fails, you may want to try adding the variable outside the quotes or totally within the blade {{}} in the form like:
<form id="application_form" method="post" action={{ "/apply/brand/".$brand-> id }} enctype="multipart/form-data">
Not sure about how the action is getting though like you have in your code above, though - you might wish to use the url() method:
<form id="application_form" method="post" action={{ url("/apply/brand/".$brand-> id) }} enctype="multipart/form-data">
change your method like this
public function apply_store(Request $request,$brand_id)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $rbrand_id,
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// Ngentod lah kalian semua, anjeng
return redirect('/apply');
}

laravel how to secure passing data from blade to controller

How can I secure data from being change if user used inspect element in chrome to change id, price..etc, I know I can't prevent users from using inspect element and do changes but I dont want these changes to have effect
I used this in blade to pass data from button using ajax
<button id="Item_root" data-id="{{$product->product_id}}" data-detailsfield="{{$product->product_details}}" data-titlefield="{{$product->product_title}}" data-pricefield="{{$product->product_price}}" data-photofield="{{ asset('images/' . $product->product_image) }}" class="Item_root Button_root">
and from inspect element user can see it like this:
<button id="Item_root" data-id="19" data-detailsfield="Serves 6-8 People" data-titlefield="Package # 8U" data-pricefield="105.99" data-photofield="http://localhost/crisp/public/images/Chicken-Fajitas.jpg" class="Item_root Button_root">
<div class="Item_image" style="background-image:url('http://localhost/crisp/public/images/Chicken-Fajitas.jpg');"></div>
<div class="Item_itemContent">
<div class="Item_topSection">
<span class="Item_name styles_just-right styles_base styles_spacing-base">Package # 8U</span>
<span class="Item_price styles_just-right styles_base styles_spacing-base styles_semibold">$105.99</span>
</div>
<div class="Item_description styles_small styles_base styles_spacing-base styles_line-default">Serves 6-8 People</div>
</div>
</button>
To preventing change values by users in inspect element and send it again to controller, you should use CSRF_TOKEN in input fields,
Take a look at here:
In laravel 5.6
<form method="POST" action="/profile">
#csrf
...
</form>
And also Laravel has Validation for check all input type that you defined.
Here is the documerntation :
Laravel Validation

how to update database using laravel controller? MethodNotAllowedHttpException No message error message

I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="post" action="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.

Symfony2 - Passing POST from plain HTML form in one controllers action to another controllers action

I've just started on using Symfony (version 2.2.1) and have ran into a little problem.
I have a plain HTML form (non-Symfony) in IntraController->indexAction and I want it to post to AuthController->loginAction. When I want to check in loginAction to see if the POST is getting passed to it, it just shows me an empty object.
My HTML form is as follows:
<form class="form-signin" action="auth/login" method="post">
<h2 class="form-signin-heading">Admin Access</h2>
<div class="input-prepend">
<span class="add-on" style="padding: 7px 9px;"><i class="icon-user"></i></span>
<input type="text" name="a_username" class="input-block-level" placeholder="Username...">
</div>
<div class="input-prepend">
<span class="add-on" style="padding: 7px 9px;"><i class="icon-lock"></i></span>
<input type="password" name="a_password" class="input-block-level" placeholder="Password...">
</div>
<button class="btn btn-success" name="post_auth" type="submit">Authenticate</button>
<a class="btn" href="../">Return to Homepage</a>
</form>
And this is how I'm trying to get the POST request in loginAction:
public function loginAction(){
return new Response(serialize($this->getRequest()->request->all()));
}
I've also tried getting a single POST item using:
return new Response(serialize($this->getRequest()->request->get('a_username')));
Sadly I'm getting an empty POST so I'm guessing that it gets emptied when it goes to auth/login. How could I preserve the POST data so it doesn't get emptied?
You are missing the CSRF key. You won't be able to use static forms like this unless you explicitly disable CSRF protection.

Categories