Laravel Basics Comprehensive Quiz & Projects
30 questions on Laravel Basics Tutorial.
Question 1: What is the primary function of Laravel Service Providers?
- A. Handling routing and rendering Blade templates to the user.
- B. Binding services, registers, and classes into the Service Container. β (correct answer)
- C. Sanitizing user input before passing it to database queries.
- D. Generating migration schemas and executing database rollbacks.
Explanation: Service providers are the central place of all Laravel application bootstrapping, responsible for registering container bindings.
Question 2: How does Eloquent's Eager Loading solve the N+1 query problem?
- A. By caching database query results indefinitely in Redis.
- B. By loading child relationships in a single query using SQL JOINs or IN clauses instead of executing a query per parent. β (correct answer)
- C. By executing queries asynchronously in background threads.
- D. By disabling database indexes during heavy read operations.
Explanation: Eager loading (using the 'with' method) fetches related data using a single query with an IN clause, preventing N additional queries.
Question 3: In Laravel's routing architecture, what is the role of Middleware?
- A. Mapping dynamic route slugs directly to view files.
- B. Providing helper functions to format dates in Blade.
- C. Filtering and inspecting incoming HTTP requests before they reach the controller. β (correct answer)
- D. Establishing persistent database connections.
Explanation: Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application (e.g. Auth, CSRF).
Question 4: What is the difference between Laravel's db:seed and database migrations?
- A. Migrations build the structure/schema of the database, while seeders populate it with test or default data. β (correct answer)
- B. Migrations run on the client side, while seeders execute exclusively on the server.
- C. Seeders compile CSS/JS assets, while migrations build the database schema.
- D. Migrations are executed once, while seeders run automatically on every request.
Explanation: Migrations are version control for database schemas. Seeders populate database tables with dummy or initial system data.
Question 5: Which Blade directive is used in a layout file to define a placeholder where child view content will be injected?
- A. @yield β (correct answer)
- B. @extends
- C. @section
- D. @include
Explanation: The @yield directive is used to display the contents of a given section defined in the child view.
Question 6: What does Eloquent's fillable property protect against?
- A. Cross-Site Scripting (XSS) in views.
- B. Mass Assignment vulnerabilities by restricting which attributes can be set via arrays. β (correct answer)
- C. SQL Injection in raw database queries.
- D. Route parameter hijacking.
Explanation: The fillable array acts as a whitelist of fields that can be modified using model create/update methods.
Question 7: What is the purpose of the App\Http\Kernel.php class in Laravel?
- A. Running command-line migrations.
- B. Configuring database connections and cache profiles.
- C. Standardizing and routing global, web, and API middleware stacks. β (correct answer)
- D. Processing queue workers and background jobs.
Explanation: The HTTP Kernel registers middleware lists, separating them into global, web, and API groups.
Question 8: Which directory holds the routing definitions for web routes?
- A. app/Http
- B. config
- C. routes β (correct answer)
- D. resources
Explanation: All route definitions reside in routes/, with web routes located in routes/web.php.
Question 9: In Laravel, how does the Request validation class report errors back to the user?
- A. By crashing the page with a stack trace.
- B. By automatically redirecting the user back with validation errors flashed to the session. β (correct answer)
- C. By saving errors to storage/logs/laravel.log.
- D. By sending email alerts to site administrators.
Explanation: If validation fails, Laravel detects the request type, redirecting back with errors automatically.
Question 10: What is the difference between Laravel queues and sync drivers?
- A. Sync processes jobs instantly in the current thread, while other queue drivers delegate execution to background workers. β (correct answer)
- B. Sync drivers are stored in SQL, while queues run on Redis.
- C. Sync drivers are only used in production environments.
- D. Queues compile Blade layouts dynamically.
Explanation: Queue drivers defer long operations (like sending emails) to run asynchronously in the background.
Question 11: How does Laravel protect forms from CSRF attacks?
- A. By validating incoming IP addresses against a whitelist.
- B. By using the @csrf directive to embed a unique, cryptographically signed token verifying requests. β (correct answer)
- C. By requiring a basic auth header for every form.
- D. By converting form fields to base64 encoding.
Explanation: The @csrf token prevents malicious scripts from submitting form queries on behalf of an active user.
Question 12: Which Artisan command creates a new controller file?
- A. php artisan controller:create
- B. php artisan make:controller β (correct answer)
- C. php artisan make:file
- D. php artisan controller:new
Explanation: make:controller generates a boilerplate controller file inside app/Http/Controllers/.
Question 13: What is the purpose of Laravel Route Model Binding?
- A. Encrypting controller models before view rendering.
- B. Automatically querying and injecting model instances into controller actions based on route parameter slugs. β (correct answer)
- C. Linking database tables without declaring foreign keys.
- D. Routing requests to different servers based on model types.
Explanation: If a route parameter maps to a model class, Laravel resolves the database row matching that ID automatically.
Question 14: What does Eloquent's dynamic property accessing do (e.g. $user->posts)?
- A. Evaluates posts as a SQL select query.
- B. Resolves the relationship query and returns a Collection of related posts, caching the result in memory. β (correct answer)
- C. Deletes matching child rows.
- D. Returns a static configuration file.
Explanation: Accessing relations as attributes fetches related records, caching them so subsequent calls don't query again.
Question 15: What is the difference between Eloquent and Query Builder in Laravel?
- A. Query Builder uses active records, while Eloquent uses plain SQL.
- B. Eloquent is an ORM with models and relationships, whereas Query Builder provides fluent, direct SQL database queries. β (correct answer)
- C. Query Builder is slower and deprecated in Laravel 9+.
- D. Eloquent does not support prepared statements.
Explanation: Eloquent sits on top of Query Builder, adding active record mapping, relations, and lifecycle events.
Question 16: Where are CSS and JavaScript raw source assets stored in a Laravel project?
- A. public/
- B. resources/ β (correct answer)
- C. storage/
- D. app/
Explanation: Source assets (to be compiled by Vite/Mix) reside in resources/, compiled files go to public/.
Question 17: What does the config:cache Artisan command do?
- A. Deletes temporary cache storage folders.
- B. Combines all configuration files into a single file to speed up application boot times. β (correct answer)
- C. Synchronizes environment keys with database columns.
- D. Restricts database connection metrics.
Explanation: Caching config files bypasses filesystem reads, optimizing production execution.
Question 18: In Laravel Eloquent, how do you define a Many-to-Many relationship?
- A. return $this->hasMany()
- B. return $this->belongsToMany() β (correct answer)
- C. return $this->hasOne()
- D. return $this->belongsTo()
Explanation: belongsToMany() indicates a pivot-table-driven relationship between two independent models.
Question 19: Which environment file is used to configure database keys and mail server credentials locally?
- A. config.json
- B. .env β (correct answer)
- C. app.php
- D. compose.yaml
Explanation: The .env file holds local configuration variables that override defaults in config files.
Question 20: What does the helper function dd() stand for?
- A. Data Directory
- B. Dump and Die β (correct answer)
- C. Dump Database
- D. Dynamic Deployment
Explanation: dd() prints variable contents cleanly and terminates script execution immediately.
Question 21: What is the difference between dynamic and static routing in Laravel?
- A. Dynamic routing allows wildcard patterns inside URL paths (e.g. {id}), while static routing matches literal paths exactly. β (correct answer)
- B. Static routing works only on static files, while dynamic routing runs controllers.
- C. Dynamic routing requires a Redis cache stack.
- D. Static routing routes queries randomly.
Explanation: Wildcard segments in dynamic routes pass variables as arguments to controller methods.
Question 22: How do you execute pending migrations in a production terminal?
- A. php artisan db:seed
- B. php artisan migrate β (correct answer)
- C. php artisan db:migrate
- D. php artisan migrate:fresh
Explanation: migrate checks the migrations table, executing only files that haven't been run yet.
Question 23: What is the purpose of Laravel Form Requests?
- A. Automatically uploading attachments to Amazon S3.
- B. Moving validation and authorization logic into dedicated, clean classes to keep controllers lean. β (correct answer)
- C. Creating HTML forms dynamically in Blade.
- D. Storing sessions inside MySQL tables.
Explanation: Form request classes validate inputs and authorize requests before the controller action runs.
Question 24: Which Blade syntax outputs raw, unescaped HTML?
- A. {{ $content }}
- B. {!! $content !!} β (correct answer)
- C. {{-- $content --}}
- D. @html($content)
Explanation: Double curly braces escape strings using htmlspecialchars. {!! !!} bypasses escaping.
Question 25: What does the php artisan migrate:rollback command do?
- A. Clears database tables and deletes columns.
- B. Reverts the very last batch of migrations that were applied to the database. β (correct answer)
- C. Deletes all php migration files from the project.
- D. Restarts the local web development server.
Explanation: Rollback targets the latest batch ID in migrations, reversing schema changes.
Question 26: What is Laravel's Eloquent 'Mass Assignment'?
- A. Assigning database rows to multiple users at once.
- B. Creating or updating a model using an associative array of inputs in a single line of code. β (correct answer)
- C. Loading all relationships dynamically.
- D. Exporting database rows to CSV files.
Explanation: Passing a payload array straight to a model represents mass assignment, requiring field whitelists.
Question 27: Which class represents a response returned by a controller action in Laravel?
- A. Request
- B. Response (or RedirectResponse, JsonResponse) β (correct answer)
- C. Controller
- D. Kernel
Explanation: Controllers must return a response object (e.g. using response() or view()) to be sent to browsers.
Question 28: How do you specify routing middleware for a group of routes?
- A. Route::group()
- B. Route::middleware() β (correct answer)
- C. Route::prefix()
- D. Route::stack()
Explanation: Route::middleware(['auth'])->group() applies middleware parameters to all nested definitions.
Question 29: What is the difference between hasMany and hasManyThrough relations?
- A. hasManyThrough accesses distant relationship data via an intermediate model (e.g., Country -> User -> Post). β (correct answer)
- B. hasManyThrough only works on databases that support foreign joins.
- C. hasMany is synchronous, while hasManyThrough is asynchronous.
- D. hasManyThrough is slower and deprecated.
Explanation: hasManyThrough handles three-table joins automatically through ActiveRecord models.
Question 30: What is the role of the storage/ directory in a Laravel application?
- A. Storing composer vendor dependencies.
- B. Storing compiled Blade templates, session files, file uploads, caches, and application log listings. β (correct answer)
- C. Housing raw database configuration files.
- D. Storing client-side javascript files.
Explanation: The storage directory stores transient runtime variables and user uploads, requiring write access.