Home > Mobile >  Laravel fetch data by something else than id
Laravel fetch data by something else than id

Time:11-12

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 ?

CodePudding user response:

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

  • Related