1/64
A collection of all multiple choice practice questions for the Laravel Junior Laravel Certification by certificates.dev
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
Route::view('/welcome', 'welcome') is defined with no explicit method. Which HTTP method does Laravel use?
GET
GET /posts/42 is requested. No Post with ID 42 exists. Route model binding is in use. What happens?
A 404 response is returned
What does Route::resource('photos', PhotoController::class) register?
All seven standard CRUD routes
What is the purpose of naming a route with ->name('posts.show')?
It allows generating URLs with route('posts.show', ...) without hard-coding the path
Given the following code block, what URL does /users resolve to?
Route::prefix('admin')->group(function () {
Route::get('/users', [AdminUserController::class, 'index']);
});/admin/users
What does $request->only('product_id', 'quantity', 'user_id') do?
Extracts only those fields from the request data
A Form Request's authorize() returns false. What does Laravel return?
A 403 Forbidden
A JSON API request fails Form Request validation. What does Laravel return?
A 422 with validation errors as JSON
What does $request->validated() return inside a Form Request controller method?
Only the fields that passed validation
Given the following validation rule, what does the confirmed rule require?
'password' => ['required', 'min:8', 'confirmed'],A password_confirmation field must be present and match password
What is the difference between {{ $variable }} and {!! $variable !!} in Blade?
{{ }} HTML-escapes output to prevent XSS; {!! !!} outputs raw, unescaped content
When is a View::composer callback executed?
Every time the specified view is rendered
You define a custom Blade directive @currency. What must the callback return?
A PHP expression wrapped in <?php ... ?> that Blade will insert into the compiled template
What does @forelse ($posts as $post) / @empty do that @foreach alone cannot?
It provides an @empty block that renders when the collection is empty
What must be done to ensure a custom Blade directive that opens a block ends cleanly in the template?
A corresponding closing directive must be registered (e.g. @endMyDirective)
What is the purpose of $fillable on an Eloquent model?
To specify which attributes can be mass assigned
Given the following code block, what does Post::published() return?
public function scopePublished($query)
{
return $query->where('status', 'published');
}A query builder scoped to published posts
What is route model binding doing in the following code?
public function show(User $user)
{
return response()->json($user);
}It automatically retrieves the user by ID from the route parameter and returns it as JSON
What does the following code print?
public function setNameAttribute($value): void
{
$this->attributes['name'] = Str::ucfirst(Str::lower($value));
}
$user = new User();
$user->name = 'LARAVELAPP';
echo $user->name;Laravelapp
What is the mistake in the following code if each post can have many comments?
$posts = Post::all();
foreach ($posts as $post) {
echo $post->comments->count();
}This causes an N+1 query problem - a new query runs for each post's comments
What is the difference between migrate:fresh and migrate:refresh?
fresh drops all tables and re-runs all migrations from scratch; refresh rolls back using down() methods and re-runs
What does $table->foreignId('user_id')->constrained() do?
Creates a user_id column and adds a foreign key constraint referencing users.id
You need to fill in a slug field when saving data. The migration defines slug as unique. A record is inserted without a slug. What error occurs?
An integrity constraint violation because the unique field cannot be null or duplicate
How do you run only the UserSeeder class without running DatabaseSeeder?
php artisan db:seed --class=UserSeeder
Schema::defaultStringLength(191) is added to AppServiceProvider::boot(). Why?
It ensures compatibility with older MySQL versions that cannot index VARCHAR(255) with utf8mb4 encoding
What does the following middleware do?
if (! auth()->check() || ! auth()->user()->is_admin) {
return redirect('/');
}
return $next($request);It checks for admin and redirects non-admins to the homepage
What does Gate::authorize('update', $post) do if the current user fails the gate check?
Throws a 403 Forbidden exception
What is the effect of a Gate::before callback that returns true?
All subsequent gate checks are skipped and the user is granted access
Who can access /dashboard given the following middleware?
Route::get('/dashboard', [DashboardController::class, 'index'])
->middleware(['auth', 'verified']);Only authenticated users whose email address has been verified
A Sanctum token was created with ['server:read', 'user:update'] abilities.
The client uses it to access an endpoint that requires admin:delete. What does Laravel return?
403 Forbidden
What does event(new UserRegistered($user)) do?
Triggers all listeners registered for UserRegistered
What is the correct way to register an event subscriber?
Event::subscribe(ActivityEventSubscriber::class)
A job class implements ShouldQueue. dispatch() is called. What happens?
The job is pushed onto the queue and handle() runs when a worker picks it up
What does SerializesModels do on an event class?
Stores the model's primary key and re-fetches the fresh model from the database when the event is handled
What does the failed() method on a queued job receive, and when is it called?
The Throwable exception; called after all retry attempts are exhausted
What happens on the second call to this code within 60 minutes?
$users = Cache::remember('active_users', 60, function () {
return User::where('status', 'active')->get();
});It retrieves the users from cache without hitting the database
What does Cache::pull('api_token') do?
Retrieves the value and removes it from cache in one operation
What is a key characteristic of the array cache driver?
It only persists in-memory for the duration of the current request
Why is Cache::add() used before Cache::increment() in the following pattern?
Cache::add('request_count', 0, 3600);
Cache::increment('request_count');
add() ensures the key exists with a baseline value of 0 before incrementing, since add() only stores if the key does not exist
What does Cache::rememberForever('app_config', fn () => AppConfig::all()) do differently than Cache::remember('app_config', 3600, fn () => AppConfig::all())?
rememberForever stores the value without an expiry - it persists until explicitly forgotten
What does collect([0, 1, 2, null, false, 3])->filter()->values()->toArray() return?
[1, 2, 3] - filter with no callback removes all falsy values
What will the following code output?
$numbers = collect([1, 2, 3]);
$numbers->map(function ($n) {
$n = $n * 2;
});
dd($numbers->toArray());[1, 2, 3] - map returns a new collection and does not mutate the original
What does ->tap() do in a collection chain?
$result = collect([1, 2, 3])
->tap(fn ($c) => Log::info('Count: ' . $c->count()))
->map(fn ($n) => $n * 2);Runs the callback on the original collection without interrupting the chain, then passes the original through
What does $data->uniqueStrict()->values()->toArray() return?
$data = collect([1, 2, '1']);[1, 2, '1'] - strict comparison keeps 1 and '1' as distinct values
What does partition() return?
[$even, $odd] = collect([1, 2, 3, 4, 5])->partition(fn ($v) => $v % 2 === 0);Two Collection instances: one for truthy results, one for falsy
What is the {file} argument in protected $signature = 'process:file {file}'?
A required argument passed as a command-line value
A file is stored with Storage::disk('public')->put('avatars/user1.png', $content). Where is it physically stored?
storage/app/public/avatars/user1.png
What does Str::replaceArray('?', ['Laravel', 'India'], 'Hello ?, welcome to ?, version ?') return?
"Hello Laravel, welcome to India, version ?" - replacements run out after two and the last ? stays
What does blank(0) return?
false - 0 is a non-blank numeric value
What does expectsOutput verify in an Artisan command test?
$this->artisan('reports:send --force')
->expectsOutput('Reports sent successfully.');The command wrote the exact string to the console output
Under what condition will an Artisan test assertion using assertExitCode(0) succeed?
When the command returns Command::SUCCESS (which equals 0)
What does $this->assertDatabaseHas('posts', ['title' => 'Hello']) verify?
At least one row in the posts table has title = 'Hello'
RefreshDatabase is used in a test. What happens after each test method runs?
The database is rolled back to its state before the test ran
Queue::fake() is called. A queued job is dispatched. What happens?
The job is intercepted and recorded so you can assert it was dispatched, without actually running it
What does assertJsonValidationErrors(['email']) verify?
The response contains a validation error for the email field
Given the following code block, What does Laravel do when calling the show method with a user ID?
// app/Http/Controllers/Api/UserController.php
public function show(User $user)
{
return response()->json($user);
}
It automatically retrieves the user by ID and returns it as JSON
Given the following code block, What is the result of implementing ShouldQueue in the following event listener?
class SendWelcomeEmail implements ShouldQueue
{
public function handle(UserRegistered $event)
{
Mail::to($event->user->email)->send(new WelcomeMail());
}
}The listener will automatically be pushed to the queue system
Given the following code block, you created a custom Form Request: php artisan make:request StoreProductRequest
What is the problem in this controller code?
//Inside the request:
public function rules(): array
{
return [
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
];
}
//In your controller:
public function store(Request $request)
{
$validated = $request->validated();
}$request should be type-hinted with StoreProductRequest
Given the following code block, Which of the following best describes this operation?
$users = User::all();
$emails = $users->pluck('email')->filter()->sort();It retrieves, filters out empty emails, and sorts the email addresses
Given the following code block, What is the purpose of the $fillable property in the Post model?
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'content'];
}To specify which attributes can be mass assigned
Given the following code block, assuming the queue worker is running, which of the following is most accurate?
// App\Jobs\SendReport.php
class SendReport implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(public User $user) {}
public function handle()
{
// Generate and email report
Mail::to($this->user->email)->send(new ReportMail());
}
}
// From code
SendReport::dispatch($user);The job will be serialized and placed on the queue, and handle() will be executed asynchronously by a worker.
Given the following code block, What is the purpose of using new \App\Rules\ValidUsername here?
Validator::make($data, [
'username' => ['required', new \App\Rules\ValidUsername],
]);It adds a custom rule that runs alongside built-in validation.
Given the following code block, What is the structure of the themes table, and what data will it contain after executing the command php artisan migrate && php artisan db:seed --class=ThemeSeeder?
return new class extends Migration
{
public function up(): void
{
Schema::create('themes', function (Blueprint $table) {
$table->id();
$table->text('title');
});
}
public function down(): void
{
Schema::dropIfExists('themes');
}
};
//
class ThemeSeeder extends Seeder
{
public function run() {
Theme::create([
'title' => 'Title',
]);
Theme::create([
'title' => 'Title',
]);
}
}The themes table consists of two fields: id (type UNSIGNED BIGINT, auto-incremented primary key) and title (type TEXT). The table contains two records: id = 1, title = 'Title' and id = 2, title = 'Title'.
Given the following code block, What happens when you visit /team/create?
//Web.php
Route::get('/team/{id}', fn ($id) => "Team $id");
Route::get('/team/create', fn () => "Create Team");It shows "Team create"
Given the following code block, What does this code do?
Route::middleware(['auth:sanctum', 'abilities:pm'])->group(function () {
//
});The code restricts access to a group of routes, allowing only authorized Laravel Sanctum users with "pm" permissions.