Jump to Category
| 💡 Laravel Fundamentals | Routing & Controllers |
| 💾 Eloquent ORM & Database | 🖥️ Frontend & Form Handling |
| ⚙️ Core Concepts |
Laravel Fundamentals
1. What is Laravel?
Laravel is a free, open-source PHP web framework based on the **Model-View-Controller (MVC)** architectural pattern. It is designed to make developing web applications easier and faster by providing a clean, elegant syntax and a rich set of built-in features for common tasks like routing, authentication, sessions, and caching.
2. Explain the request lifecycle in Laravel.
The request lifecycle begins when a request hits the `public/index.php` file.
- The autoloader, application instance, and HTTP kernel are bootstrapped.
- The incoming HTTP request is captured as a `Request` object and sent through the HTTP kernel.
- The request passes through the global **middleware** stack.
- The **router** dispatches the request to a controller action or a closure route.
- Route-specific middleware is executed.
- The controller action executes business logic and returns a `Response` object (often by returning a view).
- The response travels back through the middleware stack.
- The HTTP kernel sends the final response back to the client.
3. What is Composer and why is it important for Laravel?
Composer** is a dependency manager for PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. It is essential for Laravel because the framework itself and all of its components (like Eloquent, Blade, etc.) are packages that are installed and managed via Composer.
4. What is the purpose of the Artisan command-line tool?
Artisan** is the command-line interface included with Laravel. It provides a number of helpful commands for developing your application. It can be used to:
- Generate boilerplate code like controllers, models, and migrations (`make:controller`, `make:model`).
- Run database migrations (`migrate`).
- Clear caches (`cache:clear`).
- Run queued jobs (`queue:work`).
- Create custom commands for your own application’s tasks.
Routing & Controllers
5. Where do you define routes in Laravel?
Routes are primarily defined in the files located in the `routes/` directory.
- `routes/web.php`: For routes that are part of the main web interface. These routes are assigned the `web` middleware group, which provides features like session state and CSRF protection.
- `routes/api.php`: For stateless API routes. These routes are assigned the `api` middleware group, which provides features like throttling.
6. What is the difference between a GET and a POST route?
This follows standard HTTP conventions:
- GET: Used to retrieve data from the server. These requests should be idempotent and should not have side effects (i.e., they should not change the state of the application).
- POST: Used to submit data to the server to create a new resource. For example, submitting a registration form.
Laravel also supports other HTTP verbs like `PUT`, `PATCH`, and `DELETE` for updating and deleting resources.
7. What are route groups and why are they useful?
Route groups allow you to apply common attributes, such as middleware or a URL prefix, to a group of routes without having to define those attributes on each individual route. This helps keep your route files clean and organized.
Example:
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', ...);
Route::get('/profile', ...);
});
8. What is a controller?
A controller is a class that groups related request handling logic. Instead of defining all of your request handling logic as closures in your route files, you can organize this logic within a controller class. Each public method in a controller can be mapped to a route to handle an incoming HTTP request.
Eloquent ORM & Database
9. What is Eloquent ORM?
Eloquent** is Laravel’s built-in Object-Relational Mapper (ORM). It provides a simple, ActiveRecord implementation for working with your database. Each database table has a corresponding “Model” class which is used to interact with that table. Eloquent allows you to query for data in your tables, as well as insert, update, and delete records, using an expressive, object-oriented syntax instead of writing raw SQL.
10. What is a migration and why is it important?
A **migration** is like version control for your database. Migrations are PHP files that contain code to define and modify your database schema (creating tables, adding columns, etc.). They are important because they allow you to evolve your database schema over time in a structured, consistent way. This makes it easy for all developers on a team to have the same database structure and simplifies the process of deploying schema changes to production.
11. Explain how to define a one-to-many relationship in Eloquent.
A one-to-many relationship is used when one model is the parent to many child models. For example, a `Post` can have many `Comment`s.
- In the parent model (`Post`), you define a `hasMany()` method: `public function comments() { return $this->hasMany(Comment::class); }`
- In the child model (`Comment`), you define the inverse relationship with `belongsTo()`: `public function post() { return $this->belongsTo(Post::class); }`
12. What is eager loading and how does it solve the N+1 problem?
The **N+1 query problem** occurs when you fetch a list of items (1 query) and then loop through them to fetch a related item, resulting in N additional queries.
Eager loading** solves this by fetching the parent models and all their related models in a constant number of queries (usually just two). You do this in Eloquent using the `with()` method. For example, `User::with(‘posts’)->get()` will fetch all users in one query, and then fetch all posts for those users in a second query, instead of one query per user.
13. What are accessors and mutators?
Accessors allow you to format Eloquent attribute values when you retrieve them from a model. For example, you can create a `getFirstNameAttribute` method to automatically capitalize a user’s name.
Mutators allow you to transform attribute values when you set them on a model. For example, a `setPasswordAttribute` method can automatically hash a password before saving it to the database.
Frontend & Form Handling
14. What is the Blade templating engine?
Blade** is the simple, yet powerful templating engine included with Laravel. Unlike some other templating engines, Blade does not restrict you from using plain PHP code in your views. All Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially no overhead to your application. Blade files use the `.blade.php` file extension.
Learn more about Blade templates.15. What is the difference between `@yield` and `@include` in Blade?
- `@yield(‘content’)`: This is used in a layout template to define a section where content will be injected. Child templates then use the `@section(‘content’)` directive to provide the content for that section.
- `@include(‘partials.header’)`: This is used to include the contents of another Blade file (a “partial”) within the current view. It’s for breaking up complex views into smaller, reusable pieces.
16. How does Laravel protect against Cross-Site Request Forgery (CSRF)?
Laravel automatically generates a “CSRF token” for each active user session. This token is verified by the `VerifyCsrfToken` middleware, which is included in the `web` middleware group. When you create an HTML form using `@csrf` in Blade, a hidden input field containing this token is automatically added. When the form is submitted, Laravel compares the token from the form with the one stored in the session. If they don’t match, the request is invalidated. This ensures that the authenticated user is the one actually making the request.
Read about CSRF Protection.17. How do you perform validation in Laravel? What are Form Requests?
Laravel provides a powerful `Validator` facade for validating incoming data. You define a set of rules (e.g., `’name’ => ‘required|max:255’`) and apply them to the request data.
A **Form Request** is a separate request class that contains both the validation logic and authorization logic for a form submission. By type-hinting the Form Request in your controller method, Laravel will automatically validate the incoming request *before* your controller code is even executed. If validation fails, an error response is automatically generated. This keeps your controllers clean and focused on business logic.
Read the documentation on Validation.Core Concepts
18. What is middleware in Laravel?
Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. They form a series of “layers” that a request must pass through before it hits your controller. Common use cases include:
- Verifying that a user is authenticated.
- Logging all incoming requests.
- Handling CORS headers.
- Checking for a maintenance mode flag.
You can create a middleware using `php artisan make:middleware`.
Read the documentation on Middleware.19. What is the Service Container?
The Laravel **Service Container** (or IoC container) is a powerful tool for managing class dependencies and performing dependency injection. It’s essentially a registry where you “bind” interfaces to concrete implementations. When you need an instance of a class, you can “resolve” it from the container, and the container will automatically inject all of its dependencies for you. This is a fundamental concept that makes Laravel’s components loosely coupled and easy to test.
Read about the Service Container.20. What is a Facade?
A Facade provides a “static” interface to services that are available in the application’s service container. For example, instead of manually resolving the cache service, you can simply use `Cache::get(‘key’)`. Under the hood, the facade resolves the service from the container and calls the appropriate method. They provide a convenient, terse syntax for using Laravel’s services.