I am getting 'Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException' as response when I am trying to check if the validator works. So when after I click the save button. This is my code :
in my view 'addMedia-partial.blade.php' :
{{ Form::open() }}
<input type="text" name="videoUrl" placeholder="enter youtube video url" />
<input type="text" name="videoTitle" placeholder="enter video title" />
<input type="text" name="videoDescription" placeholder="enter video description" />
<input type="submit" value="Save">
{{ Form::close() }}
in my routes.php :
Route::get('/guide/dashboard/media/add/storeVideo', array('as' => 'guide-video-add','uses' => 'MediaController#getNewVideo'));
Route::post('/guide/dashboard/media/add/storeVideo', array('uses' => 'MediaController#postNewVideo'));
in my controller MediaController.php :
public function postNewVideo()
{
$rules = array('videoUrl' => 'required', 'videoTitle' => 'required|min:5', 'videoDescription' => 'required|min:20');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
//return Redirect::route('guide-media-add')->withErrors($validator);
//gaat niet omdat dit in een andere controller is ??
return Redirect::route('guide-video-add')->withErrors($validator);
}
}
public function getNewVideo()
{
return View::make('guide.dashboard.dashboard')->nest('child', 'guide.dashboard.addMedia-partial');
}
Please check with Firebug which URL and which type of request are you sending.
Secondly please execute php artisan route:list This will show you all the routes and which method they accept.
There must be mismatch between defined and actual requests. You must be sending POST to the route which only accepts GET.
Related
I am having trouble running the following code to update my database with the form input the user has filled in. The ideal output would be to be redirected to my pageManagement.blade after updating the record in the database. The current output is an error message: Call to a member function update() on string.
The code I have used is shown below.
PageController#update function.
public function update($URI)
{
$data = request()->validate([
'title' => 'required',
'URI' => 'required|min:5|max:10',
'pageContent' => 'required'
]);
$URI->update($data);
return redirect('/p');
}
editPage.blade.php
<h1>Fill in the form to edit a page below.</h1>
<form action="/page/{{ $pageContent->URI }}" method="post">
#csrf
#method('PATCH')
<label for="title">Title:</label><br>
<input type="text" id="title" name="title" autocomplete="off" value="{{ $pageContent -> title
}}"><br>
#error('title') <p style="color: red">{{ $message }}</p> #enderror
<label for="URI">URI:</label><br>
<input type="text" id="URI" name="URI" autocomplete="off" value="{{ $pageContent -> URI }}">
<br>
#error('URI') <p style="color: red">{{ $message }}</p> #enderror
<label for="pageContent">Page Content:</label><br>
<textarea id="pageContent" name="pageContent" value="{{ $pageContent -> pageContent }}">
</textarea>
#error('pageContent') <p style="color: red">{{ $message }}</p> #enderror
<input type="submit" value="Submit">
</form>
THE SCRIPT SRC SHOULD BE HERE BUT HAS NOT BEEN INCLUDED DUE TO THE INDENTATION ISSUE WITH
STACKOVERFLOW.
<script>
tinymce.init({
selector:'#pageContent'
})
</script>
Web.php file where I store my routes.
Route::patch('/page/{URI}','PageController#update');
My GitHub repository link is attached below if you want a better view of the code.
https://github.com/xiaoheixi/wfams
Thanks for the help everyone!
The error is coming from a non-instantiated object URI. You are passing a string from your form - whatever $pageContent->URI is. Without loading the object you wish to update, it is just a string, thus the error message.
$URI->update($data);
at the end of your method is basically saying something like 'call update on the number 32' (32->update($data)).
To fix the error in your question, you can instantiate the object at the beginning of your method:
public function update($URI)
{
$data = request()->validate([
'title' => 'required',
'URI' => 'required|min:5|max:10',
'pageContent' => 'required'
]);
$obj = \App\URIModel::find($URI); // Whatever the model is
$obj->update(request()->all());
return redirect('/p');
}
Alternate Fix: Since you have the named variable inside the route file, you can also take advantage of route-model binding by injecting the model directly in the method() to save a line of code:
public function update(\App\URIModel $URI)
{
$data = request()->validate([
'title' => 'required',
'URI' => 'required|min:5|max:10',
'pageContent' => 'required'
]);
$URI->update(request()->all);
return redirect('/p');
}
while passing variable in URL to edit and update a form it's returning only 404 not found , the tutorials did not help me , so this is my code :
controller : rendezv.php
public function editer ($id) {
$rdv= rendezvous::findOrFail('id');
return view ('/edit', ['modifier'=>$rdv]);
}
public function update(Request $request ,$id)
{
$this->validate($request, [
'email' => 'required' ,
'tel' => 'required'
]);
//modifier rendez vous
$editer=rendezvous::findOrFail('id');
$editer->Email = $request->input('email');
$editer->tel = $request->input('tel');
$editer-> save();
return redirect('/index');
}
and this this edit.blade.php
<form action="/update/{{$modifier->id}}" method="post" role="form" data-aos="fade-up">
#csrf
<input type="hidden" name="_method" value="PATCH" />
<input placeholder="{{$modifier->Email}}" type="email" class="form-control" name="email" id="email" data-msg="Please enter your name " />
<input placeholder="{{$modifier->Numéro_de_téléphone}} " type="text" class="form-control" name="tel" id="subject" data-rule="minlen:8" data-msg="Please enter at least 8 numbers" /> </i>
<div id="buttons">
<button type="submit" class="btn btn-primary"> modifier </button>
</div>
</form>
and finally route :
Route::get('/rendezvous_{ID}', 'doctor#rdv');
Route::post('/rdv','rendezv#rdv');
Route::post('/bienvenu','doctor#authentification')->name('aziz');
Route::get('/edit/{id}','rendezv#editer');
need yr help guys , and thank you
Please add the route for update
Route::patch('/update/{id}','rendezv#update');
You get 404 for both edit and update for findOrFail() method. You are passing string 'id' instead of $id.
In editer method please replace
$rdv= rendezvous::findOrFail('id');
with
$rdv= rendezvous::findOrFail($id);
In update method please replace
$editer=rendezvous::findOrFail('id');
With
$editer=rendezvous::findOrFail($id);
Furthermore, findOrFail() method will return 404 if no data is found with the given $id
You route /update/{{$modifier->id}} doesn't exist, you need to declare it in you router file:
Route::post('/update/{id}','rendezv#update');
Take a look at the Resource Controllers
What you are looking for is a Route::post('/edit/{id}','rendezv#update'); or put or patch
You are missing a post route:
Route::post('/edit/{id}','rendezv#update');
The following is my blade :
<form action="{{route('ans1.eval')}}" method="post">
<br>
<input type="radio" name="evaluate" class="evaluate" value=10> 1
<input type="radio" name="evaluate" class="evaluate" value=15> 1.5
<input type="radio" name="evaluate" class="evaluate" value=20> 2
<input type="radio" name="evaluate" class="evaluate" value=25> 2.5
<input type="radio" name="evaluate" class="evaluate" value=30> 3
<button type="submit" class="btn btn-primary" align="right">Evaluate Answer</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
The following is my route :
Route::post('/evaluateans', [
'uses' => 'AnswerController#postEvaluateAns',
'as' => 'ans1.eval',
'middleware' => 'auth'
]);
The following is my validation :
public function postEvaluateAns(Request $request)
{
$this->validate($request, [
'evaluate' => 'required'
]);
}
The following is the error when no evaluation is selected :
MethodNotAllowedHttpException in RouteCollection.php line 218
From the laravel docs on validation
If the validation rules pass, your code will keep executing normally;
however, if validation fails, an exception will be thrown and the
proper error response will automatically be sent back to the user. In
the case of a traditional HTTP request, a redirect response will be
generated.
When your validation fails it redirects back with a GET method (a redirection uses the GET method) but if you show the form from a route that is not a GET one it throws this error.
So you have to show the form with a GET route.
As alternative you can manually create your validator so you can choose the redirect GET route in case of failed validation, e.g.:
public function postEvaluateAns(Request $request)
{
$validator = Validator::make($request->all(), [
'evaluate' => 'required'
]);
if ($validator->fails()) {
return redirect('failed_validation_GET_route')
->withErrors($validator)
->withInput();
}
return redirect()->route('success_GET_route')
->with('status', 'Success!');
}
I used 5.4 and I've an index action in convert controller which shows the form and then have another action calculate in the convert controller. So the form has from-currency, amount, to-currency input and all of them are required.
Here's the validation I've for calculate action:
$this->validate(request(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
If the validation failed I want when showing the errors and the form it will prepopulate the input already.
Is there like a function I can use for Request ? I know how to get the domain/path inside blade like Request::root() and I also tried Request::input('from_currency) in the view but not work.
I even tried to set the view data like 'from_currency' => request('from_currency') and it's blank. Any idea?
When you are validating your form your request if it fail you can redirect to the same page with all the input which was submited
$validator = Validator::make($request->all(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
if ($validator->fails()) {
return redirect('index')
->withErrors($validator)
->withInput();
}
and in your blade view you can show the old value by ussing the old helper like this
<input type="text" name="from_currency" value="{{ old('from_currency') }}">
<input type="text" name="to_currency" value="{{ old('to_currency') }}">
<input type="text" name="amount" value="{{ old('amount') }}">
Try this
In your blade file, make sure your inputs have this:
<input type="text" ... value="{{ old('from_currency') }}" ... >.
Then in your controller...
if($validation->fails()) {
return redirect()->back()->withInput();
}
You can also user Validate instead of Validator::make.
eg
$this->validate($request, [
'question' => "required|min:10|max:100",
'answer' => "required|min:20|max:300",
'rank' => "required|numeric|gt:0|lt:100",
]);
Then in your form use
<input type="text" class="form-control" id="question" name="question" value="{{ old('question') }}">
This will automatically redirect back with input if the validator fails.
This way, you DO NOT have to include
if($validation->fails()) {
return redirect()->back()->withInput();
}
I have a number of php files in my project:
admin.blade.php: this files contains the admin form.
When called it show the following error:
MethodNotAllowedHttpException in RouteCollection.php line 201
<h2>Please Log In To Manage</h2>
<form id="form1" name="form1" method="post" action="<?=URL::to('/admin')?>">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
User Name:<br />
<input name="username" type="text" id="username" size="40" />
<br /><br />
Password:<br />
<input name="password" type="password" id="password" size="40" />
<br />
<br />
<br />
<input type="submit" name="button" id="button" value="Log In" />
</form>
In route.php, this call is made:
Route::get('/admin',array('uses'=>'student#admin'));
This is the function in student.php
public function admin()
{
return View::make('student.admin');
$validator = Validator::make($data = Input::all() , User::rules());
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
else
{
$check = 0;
$check = DB::table('admin')->get();
$username = Input::get('username');
$password = Input::get('password');
if (Auth::attempt(['username' => $username, 'password' => $password]))
{
return Redirect::intended('/');
}
return Redirect::back()->withInput()->withErrors('That username/password combo does not exist.');
}
}
I don't know much about creating an admin area, I am just trying to create it.
This is how I do it.
Routes.php
Route::get('/admin', 'UsersController#getAdminLogin');
Route::get('/admin/dashboard', 'UsersController#dashboard');
Route::post('/admin', 'UsersController#postAdminLogin');
admin_login.blade.php
{!! Form::open(['url' => '/admin']) !!}
<div class="form-group">
{!! Form::label('email', 'Email Id:') !!}
{!! Form::text('email', null, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}
</div>
{!! Form::close() !!}
dashboard.blade.php
<h4 class="text-center">
Welcome {{ Auth::user()->full_name }}
</h4>
UsersController.php
/**
* Display the admin login form if not logged in,
* else redirect him/her to the admin dashboard.
*
*/
public function getAdminLogin()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return redirect('/admin/dashboard');
}
return view('admin_login');
}
/**
* Process the login form submitted, check for the
* admin credentials in the users table. If match found,
* redirect him/her to the admin dashboard, else, display
* the error message.
*
*/
public function postAdminLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email,role,admin',
'password' => 'required'
]);
$credentials = $request->only( 'email', 'password' );
if(Auth::attempt($credentials))
{
return redirect('/admin/dashboard');
}
else
{
// Your logic of invalid credentials.
return 'Invalid Credentials';
}
}
/**
* Display the dashboard to the admin if logged in, else,
* redirect him/her to the admin login form.
*
*/
public function dashboard()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return view('admin.dashboard');
}
return redirect('/admin');
}
Your Code:
In routes.php, you have only 1 route, i.e.,
Route::get('/admin',array('uses'=>'student#admin'));
And there is no declaration of post method, hence, the MethodNotAllowedHttpException
Also, in your controller, you are returning the view first and then processing the form which is not going to work at all. You first need to process the form and then return the view.
public function admin(){
// Won't work as you are already returning the view
// before processing the admin form.
return \View::make(students.admin);
// ...
}
As #Sulthan has suggested, you should use Form Facade. You can check out this video on Laracasts about what Form Facade is and how you should use it.
You're using post method in the form but you're having get method in the routes.
So, Change the method to post in your routes
Note :
I recommend you to make use of the default form opening of Laravel like the below given which is always the best practise
{!! Form::open(array('url' => 'foo/bar')) !!}
{!! Form::close() !!}
Tips :
Read more on here and try to debug such things by comparing the methods and routes.
Form facade is not included in laravel 5 by default. You shall install it by
composer require "illuminate/html":"5.0.*"
and updating in the app.php.
I have written a blog which gives a breif about this installation.
In Routes web.php
Your code is
Route::get('/admin',array('uses'=>'student#admin'));
which is wrong.
Actually submitting data in POST method its array of data so you need to route through post instead of get.
so correct code is
Route::post('/admin',array('uses'=>'student#admin'));
Follow this tutorial form Laracast it might helpful,
https://laracasts.com/series/laravel-from-scratch-2017/episodes/16
In routes.php, replace Route::get by Route::post.
You have no post route for your form data posting , use route match function for both http verb (get & post). use this
Route::match(['get', 'post'], '/admin', 'student#admin');
Also you need to change your admin method,
public function admin(Request $request){
if($request->isMethod('get')){
return \View::make('student.admin');
} else {
// your validation logic
}
}