how to display data from database in laravel , i stuck in ( $reviews is undefined )

Hi Sorry iam new in laravel , iam tring to display data from DB but i get error ($reviews is undefined) in home.blade . Plz help "

web.php :

use App\Http\Controllers\ReviewController; use Illuminate\Support\Facades\Route; Route::get('/', function () {return view('home');});Route::get('/car', function () {return view('car');});Route::post('home',[ReviewController::class, 'reviewstore'])->name('');

home.blade :

<br/> @foreach ($reviews as $review)
    {{ $review['name']}}  

ReviewController :

namespace App\Http\Controllers; use App\Models\ReviewRating; use Illuminate\Http\Request; class ReviewController extends Controller { public function index(){
    $reviews = ReviewRating::all();
    return view('home', ['reviews' => $reviews]);
public function reviewstore(Request $request){
    $review = new ReviewRating();
    $review->name    = strip_tags($request->input('name'));
    $review->comments = strip_tags($request->input('comment'));
    $review->star_rating = strip_tags($request->input('rating'));
    return redirect()->back()->with('flash_msg_success','Your review has been submitted Successfully,');
}  }

My Model :

namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class ReviewRating extends Model {use HasFactory;
protected $fillable = [

>Solution :

In your Route::get('/', function() code, you don’t call the ReviewController index method.

Change it to this and you should be ok

Route::get('/', [ReviewController::class, 'index']);

If you want to keep your ‘/’ route definition like it is then add the ‘reviews’ variable

Documented here.

Route::get('/', function () {
    $reviews = ReviewRating::all();

    return view('home', ['reviews' => $reviews]);

Leave a Reply