简体   繁体   中英

Laravel fetch data by something else than id

So I'm a total newbie in laravel and I don't know if it can be done but I saw that in the controller I can display data of a specific 'id' with this in my api.php:

Route::get('books/{id}', 'App\Http\Controllers\BooksController@getBookById');

And this in my 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);
}

I'm using Angular for the front and I have a searchbar to search by 'title' of a book, so in my database I have a column 'title' and I want to fetch data by 'title' instead of 'id'. Is it possible ? And if yes how ?

I'm thinking you're wanting to retrieve the book based on user input...? You can inject the request in your method. Also you don't need to explicitly handle 404 and response codes.

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();
}

Validation docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM