user8943958
user8943958

Reputation:

Laravel post request not works

I have Form in Laravel and when i submit the form to redirect another page("action = panel") with inputs's value. but problem is that when i enter in another's link it displays error. what is wrong?

This is form

enter image description here

this is another page when submit form

this is error when i enter in link again

this is form code:

<form action="{{route('adminPanel')}}" class="form" method="POST">
    <p>Name:</p>
    <input type="text" name="name"><br>
    <p>Password:</p>
    <input type="password" name="password"><br>
    <input type="submit" name="submit" value="Enter As Admin" class="submit">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

this is routes:

Route::get('/', [

    'uses' => 'AdminController@getAdminIndex',

    'as' => 'index.admin'
]);
Route::post('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);

this is controller:

class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
        return view('admin/admin', ['name' => $request->name]);
    }
}

Upvotes: 1

Views: 82

Answers (3)

pedram afra
pedram afra

Reputation: 1213

this is because when you enter an address in address bar, your are actually sending a get request. but you've defined your route with post method!
to fix this you can use any:

Route::any('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);

and in controller:

use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
       $name = $request->name ?: Auth::user()->name; 
       return view('admin/admin', ['name' => $name]);
    }
}

Upvotes: 1

user7325973
user7325973

Reputation: 182

Sometimes routes may create you an issue. Try below snippet.

<form action="{{route('adminPanel')}}" class="form" method="POST">
  <p>Name:</p>
  <input type="text" name="name"><br>

  <p>Password:</p>
  <input type="password" name="password"><br>

  <input type="submit" name="submit" value="Enter As Admin" class="submit">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Correct your Routes as below and try.

Route::post('/adminPanel', ['uses' => 'AdminController@getAdminPanel', 'as' => 'adminPanel' ]); 

Upvotes: 0

Try to use the following statement in form as {{ csrf_field() }}

Upvotes: 0

Related Questions