I'm a beginner to Laravel. I've created a simple blog. In the page that lists the posts for the admin, i've put a delete
link with the post id attached as a parameter.
This link is to an action called deletePost
, Just wrote its declaration nothing more.
Whenever i access the route public/admin/post
, I get this message :
Unknown action [PostController@deletePost].
Here's my Controller class :
class PostController extends BaseController {
public function listPosts(){
$posts = Post::all();
return View::make('admin.post.list')->with('posts' , $posts);
}
public function addPost(){
$data = Input::all();
$rules = array(
'title' => 'required|min:3',
'body' => 'required|min:10',
);
$validator = Validator::make($data, $rules);
if($validator->passes()){
$post = new Post();
$post->title = htmlentities(trim($data['title']));
$post->body = strip_tags($data['body'], '<strong><pre>');
$post->save();
return View::make('admin.post.add')->with('message' , 'Post successfuly added.');
} else {
return Redirect::to('admin/post/add')->withErrors($validator);
}
}
public function deletePost($id){
return $id;
}
}
And my routes :
Route::group(array('prefix' => 'admin'), function(){
Route::get('/' , function(){
return View::make('admin.main')->with('title', 'Main');
});
Route::group(array('prefix' => 'post'), function(){
Route::get('/', "PostController@listPosts");
Route::get('add', function(){ return View::make('admin.post.add'); });
Route::post('add', "PostController@addPost");
});
});
And finally the view that produces this error :
@extends('layout.layout')
@section('header')
@stop
@section('content')
<h2>Main - Admin - Post Main menu</h2>
<ul>
<li><a href="{{ url('admin/post/add') }}">Add</a></li>
</ul>
@if(isset($posts))
@foreach($posts as $post)
<p>{{ $post->body }}</p>
<a href="{{ action('PostController@deletePost', array('id' => $post->id)) }}">Delete</a>
@endforeach
@endif
<a href="{{ url('admin/') }}">Back</a>
@stop
Looks like you need to set a route for the deletePost action. Assuming your url is admin/post/delete/$id
, try adding this as a new line for your post group in routes.php:
Route::get('delete/{any}', "PostController@deletePost");
Instead of using {{ action('PostController@deletePost', array('id' => $post->id)) }}
to build your URL, you could use link_to_action()
helper in your view to build the entire anchor including HTML tags/attributes/etc:
{{ link_to_action('PostController@deletePost', 'Delete', $parameters = array($post->id), $attributes = array()) }}