Using Form button/Eloquent to set an entire column to null - php

I am having a real issue getting a button to scan and clear out an entire column using an eloquent model. I have two columns in my SQLite DB, "States" and "Totals"... I want the States to stay in their own order, but I want the totals to be cleared out upon the user selecting a button. The character type for 'totals' is BigInt... After the user selects the button, I want them redirected to the home page (with the values cleared so they can start over).
Here are my routes:
Route::resource('states', 'StateController');
Route::get('/', 'StateController#index');
Route::post('create', 'StateController#store');
Route::post('states.update', 'StateController#update');
Here is my controller:
public function update()
{
Distributors::update(['total' => null]);
return View::make('states');
}
Here is my form:
{{ Form::open(['route' => 'states.update']) }}
{{ Form::submit('Destroy and Start Anew') }}
{{ Form::close() }}
The error I get is:
MethodNotAllowedHttpException
Is there a simple issue with my routes? I can't figure it out.

You did not specify a method attribute on your form, so it will automatically execute a GET request. Your state.update route is only setup to accept POST requests.
Change your form to this:
{{ Form::open(['route' => 'states.update', 'method' => 'post']) }}

Please delete
Route::resource('states', 'StateController');
in your route and try again.

Related

MethodNotAllowedException when send post form with csrf_token Laravel 5.4

I'm trying to access my "store" (POST) method from my route resource. I call the ProductCRUD.store method from a form that can have different input depending on the previous page. I mean by that, depending if the object i receive have certain boolean value, the input is shown.
#if($category->havePrice == 1)
{!! Form::label('price', 'Price') !!}
{!! Form::text('price', '', array('id' => 'price', 'name' => "price") !!}
#endif
When I click on the button to send the form, I got a message saying
MethodNotAllowedHttpException in RouteCollection.php line 251:...
I tried to add a csrf token with the method csrf_field() too.
I tried to empty the cache of laravel with those two methods:
php artisan cache:clear
php artisan route:cache
I tried to create a personal route like this:
Route::post('/product/store', array('as' => 'product', 'uses' => 'ProductController#store'));
None of those solution works. Always that exception.
My current code:
Route:
Route::resource('ProductCRUD','ProductController');
Form
<form method="POST" action="{{route('ProductCRUD.store')}}">
{{ csrf_field() }}
Controller method:
public function store(Request $request) {
$newGameModel= new GameModel();
$category = $this->CategoryRepo->getByID($request->category);
$this->validate($request, [
'name'=> 'required',
'picture'=> 'required|image|mimes:jpg,jpeg,gif,png|max:5000',
'quantite' => 'required|min:0',
'price' => 'required_if:'.$category->havePrice.',1',
]);
...
}
If I remove the "$this->validate(...)" method the code continues to execute (no more MethodNotAllowedException error). I tried to comment one by one validation it changes nothing.
Plus, if I reload the page, the input error are shown correctly. If i click again to send the form, surprise! The error again.
Edit:
I send my form using only a button and the form, no ajax:
{!! Form::submit('Next step', 'name'=>"accept", 'methode' => "post")) !!}
Plus, I can access my controller code. If I remove the validate method, everything work find
Do you guys have any idea why it's doing that? Thank you for your time!
Ok, so I found the problem and how to fix it (not what I wanted to do).
First, I don't have any error in my code. My post, csrf and my routes are all good.
The problem is how larval validates things. For example, If your first page was a post form and your second page is also a post form, when you validate on the second page and it fails, it will try to return to the second page to show the error. But the fact is, it can't find the response of your first page, so you got an error like I got.
I fix it by removing the first form (it was, for me, a little information I can put somewhere else). But I don't know if there is a better way to fix it.

Passing an id from a select list in a form, getting "non-object" error, Laravel-4

On a dashboard page, I've created a select list in a form that lists the names of components; the value that's passed from the select list is obviously the component id. On pressing submit, the user is routed to a page that displays the data about that component. Should be dirt simple...
Controller:
public function showDashboard()
{
$components = Component::lists('name','id'); ...
return View::make('dashboard', array('components'=>$components, ...))
}
dashboard.blade.php:
{{ Form::open(array('route' => array('components.show', $components->id), 'method'=>'get')) }}
{{ Form::Label('id','Component:') }}
{{ Form::select('id', $components) }}
{{ Form::submit('Show Component', array('class'=>'button')) }}
{{ Form::close() }}
I've tried various ways of doing this, and get a different error every time. The above code doesn't even let me display the dashboard page -- I get a "Trying to get property of non-object" error. Clearly, it's not liking $components because that was passed as a list array and not an object. As I said, I'm sure this is dirt simple, I just can't figure out the proper syntax, and Laravel docs aren't giving me the answer. Thanks!
The problem isn't the dropdown, or the lists method, but rather in your form opening. Here, you have $components->id as an argument to the route, but $components is an array and you can't access an id property on it.
Finally figured this out. I had posted a similar question here subsequent to this one, and rather than repeat the answer, it is here:
How to pass id value from select list to controller when controller expects an object? laravel-4
The very short version: change Route::get to Route::post. Details with code in the link above. Problem solved!

Laravel 4.1 - passing resource ID from form <select> to controller method?

Sorry if this is a stupid question. I'm very new to laravel / MVC, and haven't had enough coffee today, so I wouldn't be surprised if the answer is sitting right in front of me. :)
background: I have a form with a select. The form is used to delete a "user" and all their associated resources from the database. The <select> is populated with unique ID's. on form submit, I would like to send a DELETE request to my Controller class, passing in the selected ID for deletion.
I can't figure out how to pass in the ID from the select, into the form. How do I make it so that when you select (for example) ID 1 in the drop down, that is passed into my resource routing on the form?
Here's some code:
{{ Form::open(array(
'url' =>'/clients',
'method'=>'delete',
'name' =>'delClient',
'role' =>'form',
'class' =>'form-horizontal')) }}
<h4>Please select the client you would like to delete:</h4>
{{
Form::selectField('delClientSelect', 'Client: ', array(
0=>'-- Select Client --')+$clientsList)
}}
{{
Form::submit('Delete Selected', array(
'class' => 'btn btn-danger confDelClient',
'data-role'=> 'delete'
))
}}
{{ Form::close() }}
Everything I read online says that you pass the id into the Form 'url' attribute, i.e:
{{
Form::open(array('url'=>'/clients/{id}'))
}}
but, as the ID is coming from the <select>, I'm not sure what the proper method is for getting the ID into my routing.
Thanks for any help!
If you are using a resource controller where you must use the DELETE verb to delete a record, then I would use jQuery to update the form URL/action to 'url'=>'/clients/{id}' as you stated.
Basically, on form submit (with jQuery that's $('form').submit()) you can append the ID from the select field to the forms url/action.
If you aren't using a resource controller, I would use the POST method, grab the ID from the select using Input::all() or Input::get() and then make your database call to delete the records from the database.

MethodNotAllowedHttpException on resource defined method Laravel-4

I created a very simple form so that I could use a submit button rather than a link to open up an edit users page. Using a link works perfectly, but the form button fails and yields a MethodNotAllowedHttpException even though the method ("edit") is perfectly defined in the UsersController resource and otherwise works fine.
Route:
Route::resource('users','UsersController');
UsersController:
public function edit($id)
{
$user = $this->user->find($id);
return View::make('users.edit')->with('user',$user);
}
show.blade.php:
<!-- This works fine: -->
{{ link_to_route('users.edit', ("Edit: " .$user->first_name." ".$user->last_name), $user->id) }}
<!-- This doesn't work, and yields the Method Not Allowed exception: -->
{{ Form::open(array('route' => array('users.edit',$user->id))) }}
{{ Form::submit('Edit User', array('class'=>'button')) }}
{{ Form::close() }}
Thanks.
When you do Form::open(), it defaults to using the post request method. But when you create a Route::resource(), the edit method takes a get request.
To make it work through the form, you'll need to open it with an additional parameter, like this:
{{ Form::open(array('route' => array('users.edit',$user->id),
'method' => 'get')) }}
You need to point to the update route, not edit.
{{ Form::open(array('route' => array('users.update', $user->id))) }}
The edit route is for displaying the view, while the update is for the put/patch request.
For more information about using the RESTful routes, I'd recommend checking out http://laravel.com/docs/controllers#resource-controllers

Laravel 4 - Multiple forms on same page?

I'm having some strange behavior with my forms in Laravel 4. I have a "settings" page with two forms, each (are supposed to) POST to a controller method, update the database and return back to the settings page. However, there seems to be an issue, either with the way my forms are working or my routes.
Here's how it is, simplified:
Settings page: (site.com/settings)
<div id="form-one" class="form-area">
{{ Form::open(array('action' => 'SettingController#editOption')) }}
{{ Form::text('optionvalue', 'Default')) }}
{{ Form::submit('Save Changes') }}
{{ Form::close() }}
</div>
<div id="form-two" class="form-area">
{{ Form::open(array('action' => 'SettingController#editPage')) }}
{{ Form::text('pagevalue', 'Default')) }}
{{ Form::submit('Save Changes') }}
{{ Form::close() }}
</div>
So basically, two seperate forms on the same page that post to two seperate methods in the same Controller - when the method is successful, it redirects them back to "settings". I won't post the methods, since tested them and they work, I believe the problem is in the routes file:
routes.php
// Checks if a session is active
Route::group(array('before' => 'require_login'), function()
{
Route::group(array('prefix' => 'settings'), function()
{
Route::get('/', 'SettingController#index');
Route::post('/', 'SettingController#editOption');
Route::post('/', 'SettingController#editPage');
});
});
Now I'm pretty sure it doesn't like the two POST routes being like that, however I cannot think of another way to do it, since the forms are on the same page. I get the error:
Unknown action [SettingController#editOption].
Since the option form comes first I guess. If I take the open form blade code out (for both), it loads the page - but obviously the form doesn't do anything.
Any help would be nice! Thanks in advance.
You can't add two same routes for different actions, because of they will be passed to first matched route and in your case to SettingController#editOption. Change your routes to :
Route::post('/option', 'SettingController#editOption');
Route::post('/page', 'SettingController#editPage');
Than in both actions you can redirect to '/': return Redirect::back(), and if error was occured:
if ($validation->fails())
{
return Redirect::to('/settings')->with_errors($validation);
}
My alternative solution for this is to create an hidden html input in each form and make the controller identify what for is submitted based in this field. So, yu can use just one route for both.

Categories