3
votes

First my error was Class Input not found so i added

'Input' => Illuminate\Support\Facades\Input::class,

in aliases array

Now when i submit my form it gives this error

ERROR: MethodNotAllowedHttpException in RouteCollection.php line 219:

Routes.php

Route::post('add', function () {
    $name = Input::get('name');
    if(DB::table('projects')->whereName($name)->first() != NULL) return 'already exist';
    DB::table('projects')->insert(array('name'=>'$name'));
    return Redirect::to('/add'); 
});

welcome.blade.php :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel Learning</title>
</head>
    <body>
            {!! Form::open(array('url' => 'add')) !!}
                {!! Form::text('name', 'Your Name...') !!}
                {!! Form::submit('Click Me!') !!}
            {!! Form::close() !!}   
    </body>
</html>

Error Snap: enter image description here

1
Does the data get inserted, though? Since you also redirect to return Redirect::to('/add');, which will be a GET url.Francesco de Guytenaere
Pass also the csrf_tokenaldrin27
@Ciccio nopx I just see that error and nothing is inserted in DB!user5913661
@aldrin27 is that must ?user5913661
From the docs If you use the Form::open method with POST, PUT or DELETE the CSRF token will be added to your forms as a hidden field automatically., so if you inspect your page source (in browser) I suspect that's already there.Francesco de Guytenaere

1 Answers

1
votes

Try to bring into practice of not using the routes.php to directly executing functions. meaning, the function used in the routes is suposed to be in a controller, maybe that is why laravel 5.1 isnt allowing you to perform the task.

to give you a better understanding of the workflow

routes.php ->

Route::resource('projects', 'projectController');

welcome.blade.php ->

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel Learning</title>
</head>
<body>
        {!! Form::open(array('url' => 'projects')) !!}
            {!! Form::text('name', 'Your Name...') !!}
            {!! Form::submit('Click Me!') !!}
        {!! Form::close() !!}   
</body>
</html>

Then, go to your cmd, browse to your project folder, and fire up the command

php artisan make:controller projectController

Here, the relevant functions you need will be automatically created for you, for ease of use of the functions, cool huh...

Now write your add logic into the create function.

public function store()
{
  Project::create(Request::all());
  //here you can write your return redirect(''); 
}

Also make sure you create a model. for example

run command

php artisan make:model Project

inside the Project model ->

protected $fillable = [
 'name'
];

the purpose of using this fillable array is for security purposes to avoid mass assignment vulnerability.

hope this helps you. feel free to ask questions