Laravel form actions leads to undefined route - laravel

Form actions always confused me as it seemed very simple just to specify the controller however, every time I use it I always get Route [Controller#method] not defined. So I always go and manually make the route then use a url for my forms.
I currently have a route set up as Route::controller('handle/events', 'EventsController') and I'm trying to call the method postAdd from a form like:
{{ Form::open(['action' => 'EventsController#postAdd']) }}
instead of using
['url' => 'handle/events/add'] which is perfectly acceptable given that this is a RESTful route.
When I use the action, Laravel throws Route [EventsController#postAdd] not defined.. The method postAdd in the EventsController also accepts a parameter which I would like to pass in the form.
In the controller, the method is
public function postAdd($staff = false) {
var_dump($staff); // Always false
}
and once again I thought it would be as simple as:
{{ Form::open(['url' => 'handle/events/add'], true) }} however it did not change the value of $staff.
Recap
I would like to change my forms to point to controller methods rather than urls.
I would like to pass a parameter with my forms.

First Problem can be solved by naming your routes.
For example: Route::post('handle/events/add',['as' => 'handle.event.add', 'uses' => 'EventsController#addMethod']);
Then in your form you can do something like this
{{ Form::open(array('route' => 'handle.event.add', 'method' =>'POST'))}}
Now your form will use EventsController#addMethod
Docs named routes
If you want to pass a parameter to the controller method you can define it in your route
Route::get('handle/{event}',['as' => 'handle.event.add', 'uses' => 'EventsController#addMethod'])
Now your addMethod expects a paramter.

Related

Submit form with route variable

I'm creating search form in laravel.
After form submit I want to get /search/{search_phrase} URL, i.e /search/cats
How do I create such URL in controler or by submitting form ?
I've tried for now (in controller) return view('search.index', ['search' => $search]); but this didn't worked.
I know I can pass variable this way: {{ Form::open(['action' => 'VentureController#searchByField', $search]) }} but this would be predefined variable and it is not working in this situation.

Laravel 5 routing within blade

up until this point I have essentially been using resource routing. One of my routes is for projects. If I create a project and then SHOW it, I see a URL in the form of
myUrl/projects/1
On the show page for a project, I want to be able to add a document. I have set up the relationships so a project can have one document and a document belongs to a project. I then set up the following route to handle the saving of the documents data
Route::post('projects/{id}/docOne', 'DocOneController#store');
So I add an a form in projects/show.blade.php, which opens like so
{!!
Form::model(new App\DocOne, [
'class'=>'form-horizontal',
'route' => ['docOne.store']
])
!!}
I then have my form fields and a save data button. Because of this new form within my projects show page, when I now show a project, it complains that the route for this new form is not defined.
How can I get this route to work within the projects show page?
Thanks
First of all you need to define a route name to your route, if you want to call it by his name.
So your route would be like:
Route::post('projects/{id}/docOne', [ //you need an array to set a route name
'as' => 'docOne.store', //here define the route name
'uses' => 'DocOneController#store' //here the callback
]);
Second you need to change your laravel form to use your route name and set the id
{!! Form::model(new App\DocOne, [
'route' => ['docOne.store', $project], //if you have setted the id variable like $id blade it gonna retturn it automatically only by passing the object, else, you can set $project->id
'method' => 'POST']
) !!}
EDIT:
You can't get an instance of a model on your view.
So the part:
{!! Form::model(new App\DocOne,
gonna fails every time you trye, also, the form:model needs an instance of a class that should have your vars filled with the info that the inputs should have (when you edit it).
You have two solutions:
If it's a new Doc and never before exist on your dataBase
I recomend to change your
Form::model
to:
Form::open
if it's a Doc thath already exist on your DB, like an edit, so in your controller you need to pass your existing Docas $docand remplace the: {!! Form::model(new App\DocOne, to:
{!! Form::model($doc,
and it works.
Form model was created to fill the input values with the data existing in your object instance, like when you edit someting.
So you need to have a correct instance.
Another think it's the MVC scope, a view shouldn't have acces to models, except if are passed by the controller.
Ok that's all.

Laravel href redirection

So I've started using Laravel and I found it very easy and now I'm creating my own restful services. My problem is I don't know if I am doing the href link correct, but yes it is working. Here is the code:
Add user
And in my controller I just render the blade:
public function create()
{
return view('accounts.create');
}
So if I click the link Add user, it will redirect me to localhost:8080/accounts/create which is working well. My question is, is there a better way of doing this? Like if ever I changed any in my routes file, I will not change anymore the href link?
Ideally, you will name the route in your routes file.
Something like,
Route::get('accounts/create', [as => 'createAccount', 'uses' => 'AccountsController#create']);
You will use it as follows
Add user
in your view.
This way, even if you change the url (accounts/create), or the action name (create), you will not have to change it in the view. Allows your view to be independent.
What you can do is give your route a name using the as key in the array in the second argument of your route:
Route::get('accounts/create', [
'as' => 'accounts.create',
'uses' => 'AccountController#create'
]);
Then you can refer to this route in your application by it's name and it'll go to the same place even if you happen to change the URL. For an anchor tag you can do the following:
{{ URL::route('accounts.create') }}
If you're using a resource controller there will be predefined routes which you can see here under Actions Handled By Resource Controller: http://laravel.com/docs/5.1/controllers#restful-resource-controllers
You can always get a quick overview of your available routes and their names by running php artisan route:list
http://laravel.com/docs/4.2/routing#named-routes
Example:
Route::get('accounts/create', array('as' => 'signup', 'uses' => 'UserController#create'));
Add user
This route is named as "signup" and you can change the url anytime as:
Route::get('accounts/signup', array('as' => 'signup', 'uses' => 'UserController#create'));
Yes, you can use the action() helper to call a method inside a controller and generate the route to it automatically on demand.
So let's consider you have a controller called FrontendController.php and a method called showFrontend( $section), and assuming that you have a route that matches this controller and method (let's say "frontend/show/{$section}", you can call:
action('FrontendController#showFrontend', array( 'index' ) )
That will return:
frontend/show/index
So basically it looks for the route associated to that method/controller. You can combine this with other helpers to create a whole URL.
NOTE: Consider the namespaces, in case that you have different folder for controllers, nested resources, etc.
I hope it helps!

Blade Form without action or url

How to generate a form by Blade template engine without generating action attribute?
I would like to generate a form just for ajax request.
1) If you dont want the form to submit
{{ Form::open(['onsubmit' => 'return false']) }}
2) If you have a ajax function, you can call it like so
{{ Form::open(['onsubmit' => 'yourAjaxFunction(); return false']) }}
3) If you want to include Angular JS directive to the form
{{ Form::open(['ng-submit' => 'submit()', 'onsubmit' => 'return false']) }}
No, it's actually not possible to tell the Form builder to omit the action attribute. Some attributes will be set in any case, and the action-attribute is one of them. Here's the relevant part from the function:
public function open(array $options = array())
{
//....
$attributes['method'] = $this->getMethod($method);
$attributes['action'] = $this->getAction($options);
$attributes['accept-charset'] = 'UTF-8';
//....
return '<form'.$attributes.'>'.$append;
}
Source: https://github.com/illuminate/html/blob/master/FormBuilder.php#L104
But you can easily overwrite it by just passing in a 'url':
Form::open(['url' => '#'])
Note: Overwriting the action like Form::open(['action' => '#']) would throw an error because this specifies the name of a route. url specifies the raw url.

Posting form in Laravel 4.1 and blade template

I'm having trouble posting forms using Laravel 4.1 with the blade template engine. The problem seems to be that the full URL including http:// is being included in the form action attribute. If I hard code the form open html manually and use a relative url, it works OK, however, when it has the full url, I am getting an exception.
routes.php
Route::any("/", 'HomeController#showWelcome');
HomeController.php
public function showWelcome()
{
echo($_SERVER['REQUEST_METHOD']);
return View::make('form');
}
Form opening tag in form.blade.php
{{ Form::open(["url" => "/","method" => "post","autocomplete" => "off"]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), ["placeholder" => "john.smith"]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", ["placeholder" => ""]) }}
{{ Form::submit("login") }}
{{ Form::close() }}
So if I go to my home dir / in the browser, I see the form that I have created. If I fill in the form details and click submit, I am simply taken to the same page - the request method is still GET as shown by echo($_SERVER['REQUEST_METHOD']);
I notice that the full
http://localhost/subdir/public/
url is used in the form markup. If I hardcode a form open tag in such as
<form action="/subdir/public/" method="post">
it works fine and $_SERVER['REQUEST_METHOD'] shows as post.
What am I doing wrong here?
You have created the route for the post?
example:
{{Form::open(["url"=>"/", "autocomplete"=>"off"])}} //No need to later add POST method
in Route.php
Route::post('/', 'YouController#postLogin');
you have not set up a route to handle the POST. You can do that in a couple of ways.
As pointed out above:
Route::post('/', 'HomeController#processLogin');
note that if you stick with your existing Route::any that the `Route::post needs to be before it as Laravel processes them in order (I believe).
You could also handle it in the Controller method showWelcome using:
if (Input::server("REQUEST_METHOD") == "POST") {
... stuff
}
I prefer the seperate routes method. I tend to avoid Route::any and in my login pages use a Route::get and a Route::post to handle the showing and processing of the form respectively.

Resources