I have a problem with Laravel framework .... I Have an HTML array of checkboxes in my Laravel view file like below:
#foreach($jobs as $job)
<input type="checkbox" name="jobs[]" value="{{$user->id}}">
#endforeach
//$jobs variable pointing to read records from jobs table in database
I want to pass "jobs" element to my Controller from the route file But I don't want to use jQuery to do it. (Should be passed with Get Method].
How can I do it?
<form method="get" action="{{route('some.route')}}">
#foreach($jobs as $job) <input type="checkbox" name="jobs[]" value="{{$user->id}}">
#endforeach
<input type="submit" value="submit">
</form>
web.php
Route::get('some/route','yourcontroller#somemethod')->name('some.route')
yourcontroller.php
public function somemethod(Request $request){
dd($request->get('jobs'));
//you an store it in database now
}
As far as I can understand your question, in order to pass data from your input to the controller you need to have a <form> that contains it, and set your method attribute to GET. From there, you can make a Route that will accept a parameter.
Read the Routing docs here.
Related
I am trying to handle a basic form with laravel and am running in to an issue where my POST route isn't being detected and is resulting in a route not defined error in the blade template. My goal is to resolve this error and post the form to the controller, then access the various form fields with the $request param.
This is the error: Route [become-a-customer] not defined.
I appreciate any suggestions on how to resolve this.
Form
<form action="{{ route('become-a-customer') }}" method="post" class="col-md-8 offset-md-2">
<div class="form-row">
<div class="form-group col-md-6">
<label for="first_name">First Name</label>
<input name="last_name" type="email" class="form-control" id="first_name" placeholder="First Name">
</div>
...
</div>
<input type="hidden" name="_token " value="{{ Session::token() }}"/>
<button type="submit" class="btn">SUBMIT</button>
</form>
web.php
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer');
BecomeACustomerController . php
class BecomeACustomerFormController extends Controller
{
public function postBecomeACustomer(Request $request)
{
$firstName = $request['first_name'];
$lastName = $request['last_name'];
...
...
return redirect()->back();
}
}
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer')->name('become-a-customer');
use this command
php artisan optimize
In Your blade Template, You have used the Named route for the form action but, it is not specified in the route file (Web.php).
Change your route file like this
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer')->name('become-a-customer');
OR, you have to change the form action like this
action="{{ url('become-a-customer') }}"
Using the named route is the best practice for a Laravel project.
you can also define as following where "as" key is for naming your route
Route::post('/become-a-customer', ['uses' => 'BecomeACustomerFormController#postBecomeACustomer', 'as' => 'become-a-customer']);
Check your Apache or Nginx configurations. Sometimes a redirect from https to http will alter the method from POST to GET.
I'd recommend setting up a temporary endpoint for GET by the same Route and placing a dd() statement in it to test the theory.
route() method uses route name which is undefined. You can define it via name() method on route as below
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer')->name('become-a-customer');
for more see doucmentation
For me url('routeName') worked instead of route('routeName')
I am trying to get a value from the url that looks more or less like this:
http://localhost:8000/new-user/7
This number 7 passed in the url as a parameters is an ID in which i submit from the blade form as a request for an action i perform in the controller but i cant get this value in anyway.
This is what i tried so far:
I tried to use this in the controller in which i submitted the form
$request->route('company_id');
I also tried to get this as a proper GET parameter:
<input type="hidden" name="company_id" id="company_id" value="{{app('request')->input('company_id')}}">
and i also tried this:
<input type="hidden" name="company_id" id="company_id" value="{{Input::get('company_id')}}">
and this:
<input type="hidden" name="company_id" id="company_id" value="{{$_GET['company_id']}}">
None os these options work and i still receive an empty value.
Any ideas or suggestions on how can i get this variable?
Thank you!
A route parameter and a query parameter are two different things.
If you have a route defined like this:
/** routes/web.php */
Route::get('/new-user/{id}', 'UsersController#show');
In this case $id is a route parameter. So to get in your blade view you could do:
/** resources/my_view.blade.php */
{{ request()->id }}
So, with a request like the one you used http://localhost:8000/new-user/7 that should output: 7.
Another case is when you have a query param. These variables doens't need to be defined in the route. For example a call of this type, using the same route defined in the previous example:
GET http://localhost:8000/new-user/7?foo=bar
^^^^^^^^
In this case the foo=bar can be accessed like this:
{{ request()->query('foo') }} // 'bar'
I am new to Laravel, I am trying to have a simple example, but I am getting a 419 error, I dont know why it shows up but I will expalin what I did,
I created a simple Controller and I called it FormController with the command line :
php artisan make:controller --resource FormController
In my web.php I added this :
Route::resource('form','FormController');
my view has a simple form in it :
<form action="/form" method="POST" >
<input type="text" name="cih">
<input type="submit">
</form>
I open my view with the create method :
public function create()
{
return view('contact');
}
I want that when I submit my form I get my data, so I use my 'store' method :
public function store(Request $request)
{
return $request->all();
}
But instead of getting it, I get 419 message, and my session has expired etc ..
I followed a course and that what the teacher was doing I believe nothing more, so I would appreciate any help, I need it.
Thank you
You need to include the CSRF token while submitting a form since the 'VerifyCsrfToken' middleware is enabled by default for the web routes in App/Http/Kernal.php.
<form action="/form" method="POST" >
#csrf
<input type="text" name="cih">
<input type="submit">
</form>
And, Welcome to Laravel!
I am wondering what is the best practive between sending data through route parameters or hidden inputs in Laravel, or in general. For example, what is the best way in your opinion between :
Route path parameters
/*** Html form --> User and Account ID are sent as route parameters ***/
<form method="post" action="/associate/user/10/account/34">
{{ csrf_field() }}
<input type="submit" />
</form>
/*** Route ***/
Route::post('/associate/user/{user_id}/account/{account_id}', 'UserController#associate');
/*** Controller ***/
public function associate($user_id, $account_id) {
$user = App\User::find($user_id);
$account = App\Account::find($account_id);
$user->account()->associate($account);
$user->save();
return back();
}
OR
Form hidden inputs
/*** Html form --> User and Account ID are sent as hidden inputs ***/
<form method="post" action="/associate/user-account">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="10" />
<input type="hidden" name="account_id" value="34" />
<input type="submit" />
</form>
/*** Route ***/
Route::post('/associate/user-account', 'UserController#associate');
/*** Controller ***/
public function associate(Request $request) {
$user = App\User::find($request->input('user_id'));
$account = App\Account::find($request->input('account_id'));
$user->account()->associate($account);
$user->save();
return back();
}
What do you think ?
Thanks a lot for your opinion.
My opinion on this is to use Route parameters where it makes sense.
It is not very clear in your example on what you're trying to achieve, i.e. having two pre-defined values as hidden inputs and just a submit button doesn't seem like a very practical real-world scenario.
Say, if you have a form to associate given user to an account, what you might be able to do is have the user_id as part of route parameters, and the account_id as a dropdown. This way your form might look something like this:
{{-- /user/{user_id}/associate-account --}}
<form action="{{ route('user.associate-account', [
'user_id' => $userId
]) }}>
{{ csrf_field() }}
<select name="account_id">...</select>
</form>
Your controller
public function associate(Request $request, $userId)
{
}
The advantages of this:
1. You can consistently group routes, related to user object.
Example:
Route::group(['prefix' => 'user/{user_id}'], function ()
{
Route::post('/associate-account', 'UserController#associate');
Route::post('/upgrade-account', 'UserController#upgradeAccount');
Route::post('/delete', 'UserController#delete');
});
As you can see it's very clear from the route that those three POST actions are all tied to given user_id
2. You can utilise Model Binding
Model Binding essentially turn your Model key, into actual Model instance, such that you can write your controller action as:
public function associate(Request $request, User $user)
{
// Here `user_id` has been converted into actual User model instance
// by default Laravel also throws ModelNotFoundException when User
// can't be found with given `user_id`
$user->account()->associate($request->get('account_id'));
}
As of Laravel 5.2 you can implicitly bind model to your route, prior to this you have to register them first.
This isn't so much a question about Laravel as it is about routing. It’s really about how you want to design your app’s routes, and what is logical to you, and those others who may work with it.
If you’re going for a more RESTful approach, the former would be better (and what I tend to prefer). It makes your routes appear logically organized, which is better suited for making api’s that others will potentially use.
Otherwise, if you don’t intend to scale your app that far, and don’t care to have an api with smexy url’s, just go with the latter approach. I only recommend you be consistent with the one you pick.
Unless I missed something (which is possible), it just looks like two ways to skin a cat.
I'm trying to create a simple search form in Symfony2.
This is my form:
<form action="/search" method="GET">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search ...">
<span class="input-group-btn">
<button class="btn-u btn-u-lg" type="button"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
So my question is, what is the syntax of the form action? Do I just enter in the exact file that receives it? Or do I need to call some kind of config file?
Another question is how do I handle the search in the controller?
Thanks in advance!
Please note that I'm a total noob in Symfony2 :)
EDIT:
How do I handle the request if I would like a nice url like this: ".../search/value" instead of ".../search?q=value"?
Here is my action:
/**
* #Route("/search/{value}", name="search")
*/
public function searchAction($value)
{
}
in your action you need to put the logical path of your controller to do so call the twig function {{path('you route alias')}} , I assume that you have already set your route configuration.
to handle search in controller that's will depend on you re own logic but in the general case you will have to get the searched word using the request object taht should be some think like that:
public function searchAction(Request $request){
$objet=$request->query->get("word");
//do staff
return $this->render('Your Bundle:views:searchResult.html.twig')
}
In the form action, you need to enter the route that points to your controller. For example if you have a route that is set up to point to "/search" which uses your searchController's search method, you'd have to write action="/search" so when a user submits this form it is going to point to your controller's method.
In your controller you can either grab the $_GET variable with the name of the input (by the way you need to add a name for your input field to be accessible via the request superglobals), or pass the value directly in your url and put an optional variable after your "/search".