Junior Laravel Developer Certification

0.0(0)
Studied by 0 people
call kaiCall Kai
Locked
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/64

flashcard set

Earn XP

Description and Tags

A collection of all multiple choice practice questions for the Laravel Junior Laravel Certification by certificates.dev

Last updated 8:21 PM on 8/20/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai
Chat

No analytics yet

Send a link to your students to track their progress

65 Terms

1
New cards

Route::view('/welcome', 'welcome') is defined with no explicit method. Which HTTP method does Laravel use?

GET

2
New cards

GET /posts/42 is requested. No Post with ID 42 exists. Route model binding is in use. What happens?

A 404 response is returned

3
New cards

What does Route::resource('photos', PhotoController::class) register?

All seven standard CRUD routes

4
New cards

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

5
New cards

Given the following code block, what URL does /users resolve to?

Route::prefix('admin')->group(function () {
    Route::get('/users', [AdminUserController::class, 'index']);
});


/admin/users

6
New cards

What does $request->only('product_id', 'quantity', 'user_id') do?

Extracts only those fields from the request data

7
New cards

A Form Request's authorize() returns false. What does Laravel return?

A 403 Forbidden

8
New cards

A JSON API request fails Form Request validation. What does Laravel return?

A 422 with validation errors as JSON

9
New cards

What does $request->validated() return inside a Form Request controller method?

Only the fields that passed validation

10
New cards

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

11
New cards

What is the difference between {{ $variable }} and {!! $variable !!} in Blade?

{{ }} HTML-escapes output to prevent XSS; {!! !!} outputs raw, unescaped content

12
New cards

When is a View::composer callback executed?

Every time the specified view is rendered

13
New cards

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

14
New cards

What does @forelse ($posts as $post) / @empty do that @foreach alone cannot?

It provides an @empty block that renders when the collection is empty

15
New cards

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)

16
New cards

What is the purpose of $fillable on an Eloquent model?

To specify which attributes can be mass assigned

17
New cards

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

18
New cards

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

19
New cards

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

20
New cards

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

21
New cards

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

22
New cards

What does $table->foreignId('user_id')->constrained() do?

Creates a user_id column and adds a foreign key constraint referencing users.id

23
New cards

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

24
New cards

How do you run only the UserSeeder class without running DatabaseSeeder?

php artisan db:seed --class=UserSeeder

25
New cards

Schema::defaultStringLength(191) is added to AppServiceProvider::boot(). Why?

It ensures compatibility with older MySQL versions that cannot index VARCHAR(255) with utf8mb4 encoding

26
New cards

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

27
New cards

What does Gate::authorize('update', $post) do if the current user fails the gate check?

Throws a 403 Forbidden exception

28
New cards

What is the effect of a Gate::before callback that returns true?

All subsequent gate checks are skipped and the user is granted access

29
New cards

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

30
New cards

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

31
New cards

What does event(new UserRegistered($user)) do?

Triggers all listeners registered for UserRegistered

32
New cards

What is the correct way to register an event subscriber?

Event::subscribe(ActivityEventSubscriber::class)

33
New cards

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

34
New cards

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

35
New cards

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

36
New cards

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

37
New cards

What does Cache::pull('api_token') do?

Retrieves the value and removes it from cache in one operation

38
New cards

What is a key characteristic of the array cache driver?

It only persists in-memory for the duration of the current request

39
New cards

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

40
New cards

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

41
New cards

What does collect([0, 1, 2, null, false, 3])->filter()->values()->toArray() return?

[1, 2, 3] - filter with no callback removes all falsy values

42
New cards

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

43
New cards

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

44
New cards

What does $data->uniqueStrict()->values()->toArray() return?

$data = collect([1, 2, '1']);


[1, 2, '1'] - strict comparison keeps 1 and '1' as distinct values

45
New cards

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

46
New cards

What is the {file} argument in protected $signature = 'process:file {file}'?

A required argument passed as a command-line value

47
New cards

A file is stored with Storage::disk('public')->put('avatars/user1.png', $content). Where is it physically stored?

storage/app/public/avatars/user1.png

48
New cards

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

49
New cards

What does blank(0) return?

false - 0 is a non-blank numeric value

50
New cards

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

51
New cards

Under what condition will an Artisan test assertion using assertExitCode(0) succeed?

When the command returns Command::SUCCESS (which equals 0)

52
New cards

What does $this->assertDatabaseHas('posts', ['title' => 'Hello']) verify?

At least one row in the posts table has title = 'Hello'

53
New cards

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

54
New cards

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

55
New cards

What does assertJsonValidationErrors(['email']) verify?

The response contains a validation error for the email field

56
New cards

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

57
New cards

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

58
New cards

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

59
New cards

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

60
New cards

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

61
New cards

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.

62
New cards

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.

63
New cards

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'.

64
New cards

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"

65
New cards

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.