In this tutorial we will show available quizzes in the homepage.
A few extra conditions for the Eloquent query:
published
quizzes.app/Http/Controllers/HomeController.php:
class HomeController extends Controller{ public function index(): View { $query = Quiz::withCount(['questions']) ->has('questions') ->when(auth()->guest() || ! auth()->user()->is_admin, function($query) { return $query->where('published', 1); }) ->orderBy('id') ->get(); $public = $query->where('public', true); $registered = $query->where('public', false); return view('home', compact('public', 'registered')); }}
And from that query we get public
and only for registered
users quizzes and pass them to the view.
From this point, we just need to show quizzes in the home view.
resources/views/home.blade.php:
<x-app-layout> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div class="p-6 text-gray-900"> <h6 class="text-xl font-bold">Public quizzes</h6> @forelse($public as $quiz) <div class="px-4 py-2 w-full lg:w-6/12 xl:w-3/12"> <div class="flex relative flex-col mb-6 min-w-0 break-words bg-white rounded shadow-lg xl:mb-0"> <div class="flex-auto p-4"> <a href="#">{{ $quiz->title }}</a> <p class="text-sm">Questions: <span>{{ $quiz->questions_count }}</span></p> </div> </div> </div> @empty <div class="mt-2">No public quizzes found.</div> @endforelse </div> </div> </div> </div> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div class="p-6 text-gray-900"> <h6 class="text-xl font-bold">Quizzes for Registered Users</h6> @forelse($registered as $quiz) <div class="px-4 py-2 w-full lg:w-6/12 xl:w-3/12"> <div class="flex relative flex-col mb-6 min-w-0 break-words bg-white rounded shadow-lg xl:mb-0"> <div class="flex-auto p-4"> <a href="#">{{ $quiz->title }}</a> <p class="text-sm">Questions: <span>{{ $quiz->questions_count }}</span></p> </div> </div> </div> @empty <div class="mt-2">No quizzes for registered users found.</div> @endforelse </div> </div> </div> </div></x-app-layout>
Now if you will add two quizzes from which one is published and public.
Guest or non admin user will see only one quiz in the public section:
And admin user will see both quizzes: