Laravel 通过 id 以外的方式获取数据
Laravel fetch data by something else than id
所以我是 laravel 的新手,我不知道是否可以完成,但我看到在控制器中我可以用这个显示特定 'id' 的数据在我的 api.php:
Route::get('books/{id}', 'App\Http\Controllers\BooksController@getBookById');
这在我的 BookController.php 中:
public function getBookByAuthor($id) {
$book = Books::find($id);
if (is_null($book)){
return response()->json(['message' => 'Book Not Found.'], 404);
}
return response()->json($book::find($id), 200);
}
我在前面使用 Angular 并且我有一个搜索栏可以按 'title' 搜索一本书,所以在我的数据库中我有一个列 'title' 我想要通过 'title' 而不是 'id' 获取数据。
可能吗 ?如果是的话怎么办?
我想您是想根据用户输入检索图书...?您可以在您的方法中注入请求。此外,您不需要显式处理 404 和响应代码。
use Illuminate\Http\Request;
use App\Models\Book;
public function getBookByAuthor(Request $request): Response
{
$input = $request->validate([
'title' => 'required|alpha_dash' // validate
]);
return Book::where('title', 'like', "%{$input['title']}%")
->firstOrFail();
}
所以我是 laravel 的新手,我不知道是否可以完成,但我看到在控制器中我可以用这个显示特定 'id' 的数据在我的 api.php:
Route::get('books/{id}', 'App\Http\Controllers\BooksController@getBookById');
这在我的 BookController.php 中:
public function getBookByAuthor($id) {
$book = Books::find($id);
if (is_null($book)){
return response()->json(['message' => 'Book Not Found.'], 404);
}
return response()->json($book::find($id), 200);
}
我在前面使用 Angular 并且我有一个搜索栏可以按 'title' 搜索一本书,所以在我的数据库中我有一个列 'title' 我想要通过 'title' 而不是 'id' 获取数据。 可能吗 ?如果是的话怎么办?
我想您是想根据用户输入检索图书...?您可以在您的方法中注入请求。此外,您不需要显式处理 404 和响应代码。
use Illuminate\Http\Request;
use App\Models\Book;
public function getBookByAuthor(Request $request): Response
{
$input = $request->validate([
'title' => 'required|alpha_dash' // validate
]);
return Book::where('title', 'like', "%{$input['title']}%")
->firstOrFail();
}