Reputation: 2824
I am recently started using laravel, i am using following restful approach, please suggest if this approach is good...
Author controller
class AuthorsController extends BaseController {
public $restful = true;
public function getIndex()
{
return View::make('authors.index')->with('title', 'Showing Authors')->with('authors', Author::all());
}
public function newAuthor()
{
if(Request::isMethod('post')){
$author = Author::create(array(
'name' => Input::get('name'),
'bio' => Input::get('bio')
));
if($author->id) return Redirect::route('authors')->with('message', 'The Author was created successfully!');
}
else{
return View::make('authors.new')->with('title', 'New Author');
}
}
}
Routes
Route::get('authors', array('as' => 'authors', 'uses' => 'AuthorsController@getIndex'));
Route::match(array('GET', 'POST'), 'authors/new', array('as' => 'new_author', 'uses' => 'AuthorsController@newAuthor'));
Please suggest if i am using correct approach for create method, and i am using same method for add form and post request.
thanks.
Upvotes: 1
Views: 113
Reputation: 3455
Your code probalby works, but you could improve it by joining your routes, controllers and migrations in one resource.
With laravel generator package
After installing that package, with the following command:
Route::resource("path","SomeController");
You will get generated resources for you app. That includes list of restful controller actions.
For example you for main GET method you will have generated index action in you controller.
Upvotes: 2
Reputation: 5526
Close. You shouldnt need to test the request method in a controller action if the routes/controller is set up properly.
Author Controller
class AuthorsController extends BaseController {
public function getIndex()
{
return View::make('authors.index')->with('title', 'Showing Authors')->with('authors', Author::all());
}
public function getNew()
{
return View::make('authors.new')->with('title', 'New Author'); //this view should contain a form that POST's to /authors/new
}
public function postNew() {
$author = Author::create(Input::all()); //note: use $fillable on your model here to prevent any extra fields from breaking things
return Redirect::action('AuthorsController@getNew')->with('message', 'The Author was created successfully!');
}
}
Routes
Route::controller("/authors", "AuthorsController")
Upvotes: 1