Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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('review.store');

home.blade :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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'));
    $review->save();
    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 = [
'id', 
'name', 
'comments', 
'star_rating',
];}

>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.
https://laravel.com/docs/10.x/views#passing-data-to-views

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

    return view('home', ['reviews' => $reviews]);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading