以下路由正常,该方法可以遍历项目: http://localhost/library/api/books
$app->get('/api/books', 'Book:getBooks');
班级:
class Book {
:
:
public function __construct($container) {
$this->container = $container;
}
public function getBooks($request, $response) {
:
:
echo '{"book": ' . json_encode($books) . '}';
}
public function getBook($id) {
echo json_encode($id);
}
}
使用由' id'标识的路由模式调用方法如下所示,不返回任何内容(空$ id): http://localhost/library/api/books/10
$app->get('/api/books/{id}', 'Book:getBook');
似乎' id'没有通过。
如何通过标识符正确处理路由模式?
答案 0 :(得分:0)
正如我在评论中所说,请告诉我们开发控制台在类别控制台和网络下的chrome中所说的内容。
我不确定你为什么选择创建这样的路线,但我会按照这种方式创建它们(看起来也更整洁):
Route::group(['prefix' => 'book'], function ()
{
Route::get('/', ['as' => 'index', 'uses' => 'BookController@index']);
Route::get('new', ['as' => 'new', 'uses' => 'BookController@new']);
Route::get('show/{bookID}', ['as' => 'show', 'uses' => 'BookController@show']);
Route::get('edit/{bookID}', ['as' => 'edit', 'uses' => 'BookController@edit']);
Route::post('create', ['as' => 'create', 'uses' => 'BookController@create']);
Route::post('update', ['as' => 'update', 'uses' => 'BookController@update']);
Route::delete('destroy/{deviceID}', ['as' => 'destroy', 'uses' => 'BookController@destroy']);
});
BookController看起来像这样:
class BookController extends Controller
{
// this shows all books and adds a pagination of 15 items, which you can easily increase or decrease
public function index()
{
$books = DB::table('books')->paginate(15);
return view('books.index', compact('books');
}
public function new()
{
$book = new Book;
return view('books.new', [
'books' => $books,
'type' => 'new'
]);
}
public function create(Request $request)
{
$this->validate($request, Book::$rules); // I put the rules inside of the Book Model, but you could just add them here aswell
$data = $request->all();
$book = new Book();
$book->fill($data);
if($book->save())
{
return redirect()->route('new')->with('success', 'success.');
}
else
{
return redirect()->route('new')->with('error', 'Error.')->withInput();
}
public function edit(Request $request, $bookID = 0)
{
$books = Book::all();
$newBook = new Book;
$book = Book::find($bookID);
if(is_null($book))
{
$books = Device::paginate(10); // paginate if you like to
return view('books.index', [
'books' => $books,
'errorNoBook' => 'No BOok'
]);
}
else
{
$bookID = $book->id;
}
return view('books.edit', [
'allBooks' => $allBooks,
'new' => $new,
'book' => $book,
]);
}
}
答案 1 :(得分:0)
以下是我发现的简单工作解决方案:
:
:
public function getBook($request, $response) {
$route = $request->getAttribute('route'); // route object
$id = $route->getArgument('id'); // route object identifier
$book = $this->db->table('books')->where('id', $id)->first();
echo json_encode($book);
}