Laravel Framework Fundamentals
Learn core Laravel framework components, routing, middleware, controllers, service containers, and dependency injection.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is Laravel and what problems does it solve?
Laravel is a PHP web application framework that provides structure, tools, and conventions so developers don't have to rebuild common functionality from scratch.
| Problem (plain PHP) | Laravel solution |
|---|---|
| Manual routing with if/switch | Expressive routing system |
| Raw SQL queries | Eloquent ORM |
| Manual session/auth code | Built-in authentication scaffolding |
| No consistent structure | MVC architecture with conventions |
It follows the MVC (Model-View-Controller) pattern and includes tools for routing, ORM, templating (Blade), queues, caching, and testing out of the box.
Q2. Explain the request lifecycle in Laravel.
1. public/index.php receives the request → 2. Bootstraps the Application (creates the service container) → 3. Kernel (HTTP or Console) handles the request → 4. Service providers are registered and booted → 5. Request passes through global middleware → 6. Router matches the route and its middleware → 7. Controller/closure handles the request → 8. Response is sent back through middleware → 9. Response returned to browser
Understanding this helps when debugging where a request 'stops' - e.g. a middleware rejecting it, or a service provider not being registered.
Q3. What is Eloquent ORM and how does it differ from raw SQL?
Eloquent is Laravel's ActiveRecord-style ORM. Each database table has a corresponding Model class used to interact with that table.
// Raw SQL
$users = DB::select('SELECT * FROM users WHERE active = 1');
// Eloquent
$users = User::where('active', 1)->get();
// Relationships in Eloquent
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class);
}
}
$post->comments; // lazy-loaded collection| Aspect | Raw SQL | Eloquent |
|---|---|---|
| Readability | Lower for complex joins | Higher, fluent chainable API |
| Relationships | Manual joins | hasMany, belongsTo, etc. |
| Database portability | SQL dialect-specific | Abstracted across databases |
Q4. What is middleware in Laravel and how do you create one?
Middleware acts as a filtering layer for HTTP requests entering your application - for example checking authentication before allowing access to a route.
php artisan make:middleware CheckAge
class CheckAge
{
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('home');
}
return $next($request);
}
}Register it in app/Http/Kernel.php, then apply it to routes:
Route::get('profile', function () {
// ...
})->middleware('checkage');| Middleware type | Example use case |
|---|---|
| Global | Runs on every request (e.g. TrimStrings) |
| Route | Applied to specific routes (e.g. auth) |
Q5. What are Laravel migrations and why are they useful?
Migrations are version control for your database schema, written as PHP code instead of manual SQL, so schema changes can be tracked, shared, and rolled back.
php artisan make:migration create_posts_table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}| Command | Purpose |
|---|---|
| php artisan migrate | Runs pending migrations |
| php artisan migrate:rollback | Reverts the last batch |
Q6. What is the difference between hasOne, hasMany, belongsTo, and belongsToMany relationships?
| Relationship | Meaning | Foreign key location |
|---|---|---|
| hasOne | One model owns one related model | On the related table |
| hasMany | One model owns many related models | On the related table |
| belongsTo | Inverse of hasOne/hasMany | On the current table |
| belongsToMany | Many-to-many relationship | Pivot table |
class User extends Model {
public function posts() {
return $this->hasMany(Post::class);
}
}
class Post extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}
class User extends Model {
public function roles() {
return $this->belongsToMany(Role::class);
}
}
Q7. What is the service container in Laravel?
The service container is a tool for managing class dependencies and performing dependency injection - it automatically resolves and injects classes your code depends on.
// Binding in a service provider
$this->app->bind(PaymentGateway::class, function ($app) {
return new StripeGateway(config('services.stripe.key'));
});
// Automatic resolution via type-hinting
class OrderController extends Controller
{
public function __construct(protected PaymentGateway $gateway) {}
}Because Laravel resolves PaymentGateway automatically, you can swap StripeGateway for a different implementation (e.g. in tests) without changing the controller.
Q8. What is the difference between $fillable and $guarded in Eloquent models?
Both control mass assignment protection - preventing attackers from setting unintended fields via bulk input like User::create($request->all()).
| Property | Behavior |
|---|---|
| $fillable | Whitelist - only listed fields can be mass-assigned |
| $guarded | Blacklist - listed fields cannot be mass-assigned, everything else can |
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
// OR
protected $guarded = ['is_admin', 'id'];
}Using $fillable is generally safer since new sensitive columns are protected by default rather than needing to be explicitly added to a blacklist.
Q9. How does Laravel's Blade templating engine work?
Blade is Laravel's templating engine that compiles templates into plain PHP code, which is then cached for performance until the source file changes.
{{-- resources/views/welcome.blade.php --}}
@extends('layouts.app')
@section('content')
<h1>Hello, {{ $name }}</h1>
@if ($user->isAdmin())
<p>Welcome, admin!</p>
@endif
@foreach ($posts as $post)
<p>{{ $post->title }}</p>
@endforeach
@endsection| Directive | Purpose |
|---|---|
| {{ }} | Echo, auto-escaped for XSS safety |
| {!! !!} | Echo raw, unescaped HTML |
| @extends / @section | Template inheritance |
Q10. What are Laravel Facades and how do they work internally?
Facades provide a static-looking interface to classes registered in the service container, giving expressive syntax without sacrificing testability.
// Using a facade
Cache::put('key', 'value', 600);
// What happens internally:
// 1. Cache::put() is intercepted by __callStatic()
// 2. Facade resolves the underlying 'cache' binding from the container
// 3. put() is called on that resolved instanceFacade class → getFacadeAccessor() returns binding key → Service container resolves the real object → Method call is forwarded to it
| Aspect | Detail |
|---|---|
| Not truly static | Underlying class is a normal object resolved from container |
| Testable | Can be mocked via Cache::shouldReceive() |
Laravel Framework Fundamentals
Learn core Laravel framework components, routing, middleware, controllers, service containers, and dependency injection.
What is Laravel and what problems does it solve?
Laravel is a PHP web application framework that provides structure, tools, and conventions so developers don't...
Explain the request lifecycle in Laravel.
Request Lifecycle Flow:1. public/index.php receives the request → 2. Bootstraps the Application (creates the s...
What is Eloquent ORM and how does it differ from raw SQL?
Eloquent is Laravel's ActiveRecord-style ORM. Each database table has a corresponding Model class used to inte...
What is middleware in Laravel and how do you create one?
Middleware acts as a filtering layer for HTTP requests entering your application - for example checking authen...
What are Laravel migrations and why are they useful?
Migrations are version control for your database schema, written as PHP code instead of manual SQL, so schema...
What is the difference between hasOne, hasMany, belongsTo, and belongsToMany relationships?
RelationshipMeaningForeign key locationhasOneOne model owns one related modelOn the related tablehasManyOne mo...
What is the service container in Laravel?
The service container is a tool for managing class dependencies and performing dependency injection - it autom...
What is the difference between $fillable and $guarded in Eloquent models?
Both control mass assignment protection - preventing attackers from setting unintended fields via bulk input l...
How does Laravel's Blade templating engine work?
Blade is Laravel's templating engine that compiles templates into plain PHP code, which is then cached for per...
What are Laravel Facades and how do they work internally?
Facades provide a static-looking interface to classes registered in the service container, giving expressive s...