Reputation: 1112
going through the tutorial on Laravel 5 here: http://laravel.com/docs/5.1/quickstart
Now, when it comes to trying to post form data to /task I get an error...
Not Found
The requested URL /task was not found on this server.
Worse, if I set up a route to GET /task and echo out something simple - this works. Is there something I am missing for a POST, please?
Here is my full route file:
<?php
use App\Task;
use Illuminate\Http\Request;
/**
* Display All Tasks
*/
Route::get('/', function () {
$tasks = Task::orderBy('created_at', 'asc')->get();
return view('tasks', [
'tasks' => $tasks
]);
});
/**
* Add A New Task
*/
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
//return redirect('/')->withInput()->withErrors($validator);
}
$task = new Task;
$task->name = $request->name;
$task->save();
//return redirect('/');
});
/**
* Delete An Existing Task
*/
Route::delete('/task/{id}', function ($id) {
Task::findOrFail($id)->delete();
return redirect('/');
});
Route::get('/task', function() {
echo 'ds';
});
Thanks folks.
DS
edit.... here is my form code I am posting with
@extends('layouts.scaffold')
@section('main')
<!-- Create Task Form... -->
<form action="/task" method="POST" class="form-horizontal">
{{ csrf_field() }}
<!-- Task Name -->
<div class="form-group">
<label for="task" class="col-sm-3 control-label">Task</label>
<div class="col-sm-6">
<input type="text" name="name" id="task-name" class="form-control">
</div>
</div>
<!-- Add Task Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Add Task
</button>
</div>
</div>
</form>
<!-- Current Tasks -->
@if (count($tasks) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Current Tasks
</div>
<div class="panel-body">
<table class="table table-striped task-table">
<!-- Table Headings -->
<thead>
<th>Task</th>
<th> </th>
</thead>
<!-- Table Body -->
<tbody>
@foreach ($tasks as $task)
<tr>
<!-- Task Name -->
<td class="table-text">
<div>{{ $task->name }}</div>
</td>
<!-- Delete Button -->
<td>
<form action="/task/{{ $task->id }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete Task</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
@endif
@endsection
Upvotes: 2
Views: 1014
Reputation: 29258
The reason Laravel couldn't resolve the POST
route is that /task
is the route's name, and not the complete address. Instead of looking for http://localhost/project/task
, it was just looking for /task
, which isn't a valid address. The solution is to use Laravel 5's url()
helper method to specify the action
of the form:
<form method="POST" action="{{ url("/task") }}">...</form>
<!-- {{ ... }} is .blade syntax for <?php ... ?> -->
Also, note the the GET
routes were working as redirect("/")
functions similarly to url("/")
Upvotes: 2