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
}
}
Related
working with Laravel 6 project and I have following CommentController,
public function update(Request $request, $id)
{
$comment = Comment::find($id);
$this->validate($request, array('comment' => 'required'));
$comment->comment = $request->comment;
$comment->save();
Session::flash('success','Comment Created');
return redirect()->route('posts.show', $comment->post->id);
}
public function delete($id)
{
$comment = Comment::find($id);
return view('comments.delete')->withComment($comment);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$comment = Comment::find($id);
$post_id = $comment->post->id;
$comment->delete();
Session::flash('success','Deleted Comment');
return redirect()->route('posts.show', $post_id);
}
and My routes are as following
Route::delete('comments/{id}', ['uses' => 'CommentsController#destroy', 'as' => 'comments.destroy']);
Route::get('comments/{id}/delete', ['uses' => 'CommentsController#delete', 'as' => 'comments.delete']);
but when I try to delete comment got following validation error message
The comment field is required.
how could I fix this problem here?
edit.blade.php
#section('content')
<div class="col-sm-6">
<form action="{{ route('comments.destroy', $comment->id) }}" method="post">
#csrf
{{ method_field('PUT') }}
<button type="submit" class="btn btn-danger btn-block">Delete</button>
</form>
</div>
</div>
</div>
#endsection
Because HTML forms can't send PUT, PATCH and DELETE requests, we must "spoof" the request and include an input field that tells Laravel which type it is sending. You can read about that here.
Technically, this means inserting the following for your delete form.
<input type="hidden" name="_method" value="delete">
Laravel comes with different helpers that help you achieve this. In your update form, you have already done this by adding the method_field('PUT');. Here, you are instructing Laravel that this is a PUT request, and we need to do this too in your delete form.
The {{ method_field('PUT') }} simply needs to change to {{ method_field('DELETE') }} or you can use the built-in #method('delete')
Like this
#section('content')
<div class="col-sm-6">
<form action="{{ route('comments.destroy', $comment->id) }}" method="post">
#csrf
#method('delete')
<button type="submit" class="btn btn-danger btn-block">Delete</button>
</form>
</div>
</div>
</div>
#endsection
You can inspect your form HTML in the browser and notice the hidden input field added automatically.
$this->validate($request, array('comment' => 'required'));
In your blade view, if you are not posting a comment in your form, you will be facing this error The comment field is required
Make sure you are posting a comment, or any typo's.
Posting your blade view would help us alot more.
Controller article
public function update(Request $request, Article $article){
$article->update($request->except('slug', 'image_path'));
if ($request->hasFile('image_path')) {
$image = $request->file('image_path');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$article->image_path = $new_name;
$article->save();
}
$article->categories()->detach();
if ($request->has('categories')) {
$article->categories()->attach($request->input('categories'));
}
$user=auth()->user();
return redirect()->back()->with('message', 'Raksts atjaunots!');
}
public function edit(Article $article){
$user=auth()->user();
return view('edit',[
'article' => $article,
'categories' => Category::with('children')->where('parent_id',0)->get(),
'delimiter' => ''
]);
}
edit blade
<form class="form-horizontal" action="{{route('update', $article)}}" method="post" enctype="multipart/form-data" style="display: flex;justify-content: center;flex-direction: column;">
<input type="hidden" name="_method" value="put">
{{ csrf_field() }}
{{-- Form include --}}
<img src="{{URL::to('/images').'/'.$article->image_path}}" alt="">
#include('partials.form')
<input type="hidden" name="modified_by" value="{{Auth::id()}}">
</form>
link to the form
<tbody>
#foreach ($articles_suggest_user as $article)
<a class="btn btn-default" href="{{route('edit', $article)}}"><i class="fa fa-edit"></i></a>
<?php } ?>
#endforeach
</tbody>
web.php
Route::get('/home/edit/{id}','Controller_Article_parents#edit', function () {
return view('/home/edit');
})->name('edit');
Route::get('/home/update/','Controller_Article_parents#update', function () {
return view('/home');
})->name('update');
When i clicked the link, i move to for example this url http://127.0.0.1:8000/home/edit/190
But my form is empty... input empty. How I can do when I open form it's display me input information ?
When click my link its display me form, but form is empty.
form example
<div class="rtq">
<label for="parent_id">Cat</label>
<span class="required">*</span>
<select
id="parent_id"
class="form-control"
name="categories[]"
multiple=""
required
>
#include('admin.categories.partials.categories',
['categories' => $categories,
'current' => $article,
'delimiter' => $delimiter])
</select>
</div>
<div class="rtq">
<label for="">Descript</label>
<textarea
name="description_short"
class="form-control"
id="description_short"
>
{{ $article->description_short ?? "" }}
</textarea>
</div>
It my form . Mini example
If you want to redirect with form input, you can use the withInput() function
return back()->withInput();
https://laravel.com/docs/7.x/redirects#creating-redirects
Now, this function is designed to be used with form validation and may not be what you want.
What I have done in the past when combining create & edit views into a single template is something like this:
{!! Form::text('name', isset($model) ? $model->name : null, [
'class' => 'form-control',
'placeholder' => 'Please fill out this field &hellips;',
'required' => true
]) !!}
This uses the Laravel Collective HTML library. However the principle is the same if you are using raw hmtl like so:
<input type="text" value="{{ isset($model) ? $model->name : null }}">
Round 2 Electric Boogaloo
You aren't returning a variable called $article to your edit.blade.php.
Round 3 Apple Tree
Originally, you appeared to be calling both a controller action AND also a callback function. Stick to the controller action only like so:
Route::get('/home/edit/{id}','Controller_Article_parents#edit')->name('edit');
Then within your edit() function on the Controller you will want to do this:
public function edit ($id) {
return view('/home/edit', [
'article' => Article::find($id)
]);
}
I'm trying to insert my data to database from form.
My URL to create the data is web.com/siswa/create
But when I click submit system show error MethodNotAllowedHttpException.
How I can fix it? Is there anything wrong with my code?
Here is my form:
<form action="{{ url('siswa') }}" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">NISN</label>
<input type="text" class="form-control" name="nisn" id="nisn" placeholder="NISN"></div>
<div class="form-group">
<label for="exampleInputEmail1">Nama Siswa</label>
<input type="text" class="form-control" name="nama_siswa" id="nama_siswa" placeholder="Nama Siswa"> </div>
<button type="submit" class="btn btn-success btn-sm font-weight-bold">Submit</button></form>
Controller:
public function tambah()
{
return view('siswa.create');
}
public function store(Request $request)
{
$siswa = new \App\Siswa;
$siswa->nisn = $request->nisn;
$siswa->nama_siswa = $request->nama_siswa;
$siswa->tanggal_lahir = $request->tanggal_lahir;
$siswa->jenis_kelamin = $request->jenis_kelamin;
$siswa->save();
return redirect('siswa');
}
Route:
Route::get('/siswa/create', [
'uses' => 'SiswaController#tambah',
'as' => 'tambah_siswa'
]);
Route::get('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
change your store function route from get to post
Route::post('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
Use Csrf protection field in your form for the session timeout error
{{ csrf_field() }}
OR
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
OR if you are using Form builder
{!! Form::token() !!}
In Route please use post instead of get
Route::post('/siswa','SiswaController#store');
and also include {{ csrf_field() }} in form
you are using method="POST" on your form but in on your route you are using Route::get
Use Route::post for your route
In your form you've given POST method, but your router doesn't have any POST handler. So all you have to do is , when you are trying to store data from form to DB you have to post the data, and the router should handle it.
Try this
Route::post('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
You are using POST method in your form and using GET in route.
try this
Route::post( '/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
] );
I'm making my first form in Laravel and the generation of the form is all working. It's just that the store function seems to blindly return the user to my contact page irrelevant of the result of the form validation.
So if the email address posted isn't an email but a random string I still get returned to the /contact page with the thank you message being sent to the view.
My controller looks like this:
namespace App\Http\Controllers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\ContactFormRequest;
class ContactController extends Controller {
public function create(){
return view('contact');
}
public function store(ContactFormRequest $request) {
return \Redirect::route('contact')
->with('message', 'Thanks for contacting us!');
}
}
And the form handler like this:
namespace App\Http\Requests;
use Illuminate\Http\Request;
class ContactFormRequest extends Request {
public function authorize() {
return true; // don't need to be registered to run form so true
}
public function rules() {
return [
'email' => 'required|email',
];
}
}
This is controlled by the following routes
if (config('app.tan_site_page_contact')===true){
Route::get('/contact', ['as' => 'contact', 'uses' => 'ContactController#create']);
Route::post('/contact', ['as' => 'contact_store', 'uses' => 'ContactController#store']);
});
And the form like this:
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
#endif
{!! Form::open(array('route' => 'contact_store', 'id' => 'contactCallMeForm')) !!}
{!! Form::label('Your E-mail Address') !!}
{!! Form::text('email', null, array('required', 'class'=>'form-control', 'placeholder'=>'Your e-mail address')) !!}
{!! Form::submit('Contact Us!', array('class'=>'btn btn-primary')) !!}
{!! Form::close() !!}
The form html seems fine,with a token and valid url
<form method="POST" action="http://localhost/contact" accept-charset="UTF-8" id="contactCallMeForm" novalidate="">
<input name="_token" type="hidden" value="VNHchLZhfsXadVZXCZWHGdAuJ4zgmO6cDJIGhR59">
<label for="Your E-mail Address">Your E-mail Address</label>
<input required="required" class="form-control" placeholder="Your e-mail address" name="email" type="text">
<input class="btn btn-primary" type="submit" value="Contact Us!">
</form>
The problem here is your ContactFormRequest class.
You extends it from invalid Request class. You extend it from \Illuminate\Http\Request class but you should extend it from \Illuminate\Foundation\Http\FormRequest (or \App\Http\Requests\Request class)
I have following routes
Route::controller('users', 'UsersController');
Controllers
class UsersController extends BaseController {
protected $layout = "layouts.login";
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getDashboard')));
}
public function getRegister() {
$this->layout->content = View::make('users.register');
}
public function logout() {
Auth::logout();
return Redirect::to('users/login')
->with('message', 'Good Bye')
->withInput();
}
public function getLogin() {
$this->layout->content = View::make('users.login');
}
public function postSignin() {
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password'),'role'=>'admin'))) {
return Redirect::to('mix/dashboard')->with('message', 'You are now logged in!');
}
else {
return Redirect::to('users/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
public function postCreate() {
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->passes()) {
// validation has passed, save user in DB
$user = new User;
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('users/login')->with('message', 'Thanks for registering!');
} else {
// validation has failed, display error messages
return Redirect::to('users/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
}
view
<div class="login-body">
<h2>SIGN IN</h2>
<form method="post" action="{{Request::root()}}/users/Signin">
<div class="control-group">
<div class="email controls">
{{ Form::text('email', null, array('class'=>'input-block-level', 'placeholder'=>'Email Address', 'data-rule-required'=>'true' ,'data-rule-email'=>'true')) }}
</div>
</div>
<div class="control-group">
<div class="pw controls">
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Password','data-rule-required'=>'true')) }}
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
</div>
</div>
<div class="submit">
<div class="remember">
<input type="checkbox" name="remember" class='icheck-me' data-skin="square" data-color="blue" id="remember"> <label for="remember">Remember me</label>
</div>
{{ Form::submit('Login', array('class'=>'btn btn-primary'))}}
{{ Form::close() }}
<div class="forget">
<span>Forgot password?</span>
</div>
</div>
Whenever i try to login it shows tokenmismatch exception error and shows following lines of filter.php
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
I have been clueless past three days...
worst is that this error automatically came , it was working fine earlier .. i did not make any changes at all !
It was client side issue
I just deleted cookies and then it start working.
You probably add the crsf filter in the /users/Signin route. You have several options:
Fistly, you can remove the crsf filter from the route.
Second, you should add the csrf token to your form input (after the <form ...> line)
{{ Form::token(); }}
Or you can change your Form declaration using the Form macro with also include the csrf token.
{{ Form::open(array('url' => 'users/Signin' ) ); }}
I hope it helps you.
Avoid having csrf on your GET routes since they don't have a token and will throw TokenMismatchException. With that said you could look at this snippet of code you could add in your controller to avoid these exceptions:
`class UserController extends BaseController {
/**
* Instantiate a new UserController instance.
*/
public function __construct()
{
$this->beforeFilter('auth', array('except' => 'getLogin'));
$this->beforeFilter('csrf', array('on' => 'post'));
$this->afterFilter('log', array('only' =>
array('fooAction', 'barAction')));
}
}
`
As you can see the CSRF filter is only being applied on the POST method and the auth one is only being applied on the getLogin controller method.