Skip to content
Advertisement

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}', 'AppHttpControllersBooksController@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 ?

Advertisement

Answer

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 IlluminateHttpRequest;
use AppModelsBook;

public function getBookByAuthor(Request $request): Response
{
$input = $request->validate([
        'title' => 'required|alpha_dash' // validate
    ]);
    return Book::where('title', 'like', "%{$input['title']}%")
        ->firstOrFail();
}

Validation docs

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement