I am fairly new to PHP & laravel so looking for some assistance.
For example , i have a table in mySQL database that stores comments by a user. The values for this table are userId,bookId & Comment. I essentially want to build a function in my controller where it will retrieve a list of comments for a specific bookId. So if bookId 'cm123' has a total of 7 comments for that book , then my function should retreive all 7 comments with a HTTP GET request. This route is strictly going into the API route , we are not using any view for this ,so forms & such for input are not needed-- rather the parameters will be manually inputted when testing the request in Postman.
Again , the end result i am aiming for is that the API returns a list of book comments stored in the database given a specific bookId input
Below are my model , route & controller classes (I do already have a function for this called "SHOW" but it is not working) :
Contoller
<?php
namespace App\Http\Controllers;
use App\Models\CreateComment;
use App\Models\BookRating;
use Illuminate\Http\Request;
class BookRatingController extends Controller
{
/**
* Display the specified resource.
*/
public function show(string $bookId): View
{
return view('CreateComment.Comment', [
'Comment' => CreateComment::findOrFail($bookId)
]);
} // return list of comments
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CreateComment extends Model
{
use HasFactory;
protected $fillable =
[
'Comment',
'userId',
'bookId'
];
}
Route
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookRatingController;
use App\Http\Models\BookRating;
use App\Http\Models\CreateComment;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('CreateRating',[BookRatingController::class, 'CreateRating']);//adding a bookrating to database API -- POST METHOD--
Route::post('CreateComment',[BookRatingController::class, 'CreateComment']);
Route::get('show/{$bookId}',[BookRatingController::class,'show']);
To achieve the above functionality first make the route as below in routes/api.php
Then modify a below function in CommentController in show function