Prepare for technical interviews with questions by technology, clear explanations, step-by-step solutions and code you can run.
Laravel is a PHP framework that saves you from building the boring parts of a website again and again. Login, routing, database handling, emails and file uploads are already there, so you can spend your time on what makes your project different. I think of it as a kitchen with all the tools laid out, so you only have to cook.
MVC splits an app into three jobs. The Model deals with data, the View is what the visitor sees, and the Controller sits in the middle. When someone opens a page, the controller asks the model for data, then hands it to the view to display. It's like a restaurant: the kitchen is the model, the waiter is the controller, and the plate on your table is the view.
Normally, if class A needs class B, you have to create B yourself. In Laravel you just mention B in the constructor and the framework builds it and hands it over. The container is the thing doing that behind the scenes, and it makes code much easier to test and swap.
They are the starting point of a Laravel app. When the app boots, it visits every provider and lets it register its services. If I'm adding my own package or custom binding, this is where I plug it in.
Middleware is like a security guard at the door. Before a request reaches the controller, it passes through middleware that can check whether the user is logged in, whether they're an admin, or whether the request should be logged. If something is wrong, the request is stopped right there.
Eloquent lets me talk to the database using PHP objects instead of writing SQL. A users table becomes a User model, and each row becomes an object. So User::find(1) does the same job as a SELECT query, but it's easier to read.
Migrations are like Git for the database structure. Instead of creating tables by hand in phpMyAdmin, I describe them in PHP files. When a teammate pulls my code, one php artisan migrate gives them the same tables I have. It also lets me roll back if I make a mistake.
A named route is a nickname for a URL. Rather than writing /user/profile/settings everywhere, I name it and call route('profile.settings'). If the URL changes later, I fix it in one place and nothing breaks.
Blade is the template engine that makes views cleaner than plain PHP. I can use @if, @foreach and @extends instead of messy PHP tags. It also escapes {{ $data }} automatically, which protects against XSS.
A facade is a shortcut that looks like a static call, such as Cache::get('key'). It isn't truly static, because it quietly fetches the real object from the container and calls the method on it. It's convenient, and it's still testable.
CSRF is when a malicious site tricks your browser into sending a request to another site. Laravel generates a secret token for each session and expects it with every form submission. That's why we add @csrf inside forms. If the token is missing or wrong, the request gets rejected with a 419 error.
Artisan is the command-line helper that comes with Laravel. I use it all the time to generate files (make:model, make:controller), run migrations, clear the cache, or list all routes. It saves a lot of typing.
The main ones are one-to-one, one-to-many, many-to-many, has-many-through, and polymorphic. A simple example: one user has many posts, and a post belongs to one user.
It happens when I load 50 posts and then, inside a loop, fetch each post's author separately. That's 1 query for the posts plus 50 for the authors. The fix is eager loading with Post::with('user'), which grabs all authors in one extra query.
A factory is a recipe for making fake records, and a seeder is the thing that runs the recipe and fills the tables. I use them when I need a lot of dummy data to test pagination or search without typing it all.
Some jobs are slow, like sending 500 emails or resizing images. If I do them during the request, the user waits and stares at a loading screen. With queues, I drop the job into a line and a background worker handles it, so the user gets an instant response.
An event says "something just happened," like a user registering. Listeners are the reactions: send a welcome email, create a profile, notify the admin. The nice part is that the registration code doesn't need to know about any of them.
I write rules like required|email|unique:users and Laravel checks the incoming data against them. If something fails, the user is sent back to the form with error messages, and their old input can be refilled. For bigger forms, I move the rules into a separate Form Request class to keep the controller tidy.
Laravel already includes the login system, sessions and password hashing. With a starter kit like Breeze, I get login, register and reset-password pages in a few minutes. For mobile apps and APIs, I'd use Sanctum for token-based login.
It holds settings that change from one machine to another, like database passwords, mail credentials and API keys. It never goes into Git. That way my local setup and the live server can use different values without changing any code.
Soft delete means the record isn't really removed. Laravel just stamps the time in a deleted_at column and hides it from normal queries. It works like a recycle bin, so I can bring the record back if someone deletes it by mistake.
It's filling a model from an array in one line, like User::create($request->all()). It's risky, because a user could sneak in a field like is_admin. So Laravel makes me list the safe fields in $fillable, and anything else is ignored.
If my route has /posts/{post} and my controller method asks for a Post $post, Laravel looks up that record automatically. If it doesn't exist, the user gets a 404. It removes the need to write Post::findOrFail($id) in every method.
Both handle authorization, meaning what a user is allowed to do. A gate is a small closure, good for simple checks like "can this user see the dashboard?". A policy is a full class tied to a model, like PostPolicy, which holds all the rules for viewing, editing and deleting posts.
Caching means saving the result of something slow so I don't repeat the work. With Cache::remember, Laravel checks whether the value is already stored, and if not it runs the code and stores it. The storage can be files, Redis or Memcached, and my code stays the same whichever I pick.
The route sends the URL to a controller method, and the method returns a view.
// routes/web.php
use App\Http\Controllers\PageController;
Route::get('/about', [PageController::class, 'about']);
// app/Http/Controllers/PageController.php
public function about()
{
return view('about', ['title' => 'About Us']);
}
One line gives me all seven standard CRUD routes.
Route::resource('posts', PostController::class);
Define table schema with foreign keys and cascade delete.
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
Define $fillable array in the model class.
class Post extends Model
{
protected $fillable = ['user_id', 'title', 'body'];
}
Use static Model::create() method passing mass-assignment array.
Post::create([
'user_id' => auth()->id(),
'title' => 'My first post',
'body' => 'Learning Laravel is fun.',
]);
Call $request->validate() with rules array and redirect on failure.
public function store(Request $request)
{
$data = $request->validate([
'title' => 'required|max:150',
'body' => 'required|min:10',
]);
Post::create($data + ['user_id' => auth()->id()]);
return redirect()->route('posts.index')->with('success', 'Post saved!');
}
Extract validation logic into FormRequest class via authorize() and rules().
// StorePostRequest.php
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'title' => 'required|max:150',
'body' => 'required',
];
}
// Controller method
public function store(StorePostRequest $request)
{
Post::create($request->validated() + ['user_id' => auth()->id()]);
return back();
}
Use hasMany() on parent model and belongsTo() on child model.
// User.php
public function posts()
{
return $this->hasMany(Post::class);
}
// Post.php
public function user()
{
return $this->belongsTo(User::class);
}
// Usage
$user = User::find(1);
foreach ($user->posts as $post) {
echo $post->title;
}
Use belongsToMany() with attach() and sync() helper methods.
// Post.php
public function tags()
{
return $this->belongsToMany(Tag::class);
}
$post->tags()->attach([1, 2]); // add tags
$post->tags()->sync([2, 3]); // keep only these
Replace lazy loading loop with eager loading Post::with("user").
// Slow: 1 + N queries
$posts = Post::all();
// Fast: 2 queries in total
$posts = Post::with('user')->latest()->get();
foreach ($posts as $post) {
echo $post->user->name;
}
Implement handle() method in middleware checking auth status or role.
public function handle($request, Closure $next)
{
if (!auth()->check() || auth()->user()->role !== 'admin') {
abort(403, 'Admins only');
}
return $next($request);
}
Use @forelse directive with @empty fallback block.
@forelse ($posts as $post)
<h3>{{ $post->title }}</h3>
<p>{{ Str::limit($post->body, 100) }}</p>
@empty
<p>Nothing here yet.</p>
@endforelse
Validate file extension/size and store file using $request->file()->store().
$request->validate([
'photo' => 'required|image|max:2048', // up to 2 MB
]);
$path = $request->file('photo')->store('photos', 'public');
auth()->user()->update(['photo' => $path]);
Use DB::table()->join() with select column filtering.
$rows = DB::table('posts')
->join('users', 'users.id', '=', 'posts.user_id')
->select('posts.title', 'users.name')
->where('posts.created_at', '>=', now()->subWeek())
->get();
Use paginate(10) in controller and {{ $posts->links() }} in Blade template.
// Controller
$posts = Post::latest()->paginate(10);
// Blade view
{{ $posts->links() }}
Create JsonResource class implementing toArray() method.
// PostResource.php
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'author' => $this->user->name,
];
}
// Controller
return PostResource::collection(Post::with('user')->paginate(10));
Verify credentials with Auth::attempt() and issue API token via createToken().
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json(['message' => 'Wrong email or password'], 401);
}
$token = $request->user()->createToken('mobile-app')->plainTextToken;
return response()->json(['token' => $token]);
}
Define fake data generator in Factory and invoke it inside DatabaseSeeder.
// PostFactory.php
public function definition(): array
{
return [
'user_id' => User::factory(),
'title' => fake()->sentence(),
'body' => fake()->paragraph(),
];
}
// DatabaseSeeder.php
public function run(): void
{
Post::factory()->count(20)->create();
}
Implement ShouldQueue interface on Job class and call dispatch().
// SendWelcomeMail.php
class SendWelcomeMail implements ShouldQueue
{
use Queueable;
public function __construct(public User $user) {}
public function handle(): void
{
Mail::to($this->user->email)->send(new WelcomeMail($this->user));
}
}
// Dispatch
SendWelcomeMail::dispatch($user);
Fire event instance with event() and handle logic inside Listener.
// Fire event
event(new UserRegistered($user));
// Listener handle()
public function handle(UserRegistered $event): void
{
Log::info('New signup: ' . $event->user->email);
}
Use SoftDeletes trait in model, add $table->softDeletes() in migration, and call restore().
// Model
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
// Usage
$post->delete(); // hidden
Post::withTrashed()->find(1)->restore(); // restored
Define scopeName() method on model accepting $query builder instance.
// Post.php
public function scopePublished($query)
{
return $query->where('status', 'published');
}
// Usage
$posts = Post::published()->latest()->get();
Use Attribute::make(get: ..., set: ...) in model class.
use Illuminate\Database\Eloquent\Casts\Attribute;
protected function name(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst($value), // reading
set: fn ($value) => strtolower($value),
);
}
Generate model Policy and call $this->authorize("update", $post).
// PostPolicy.php
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
// Controller method
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// ...proceed with update
}
Use actingAs() for auth session, post() for requests, and assertDatabaseHas() for DB checks.
public function test_logged_in_user_can_create_a_post()
{
$user = User::factory()->create();
$response = $this->actingAs($user)->post('/posts', [
'title' => 'Test title',
'body' => 'This is a long enough body text.',
]);
$response->assertRedirect('/posts');
$this->assertDatabaseHas('posts', ['title' => 'Test title']);
}
Try searching for keywords like "JWT", "Express", "useEffect", "PDO", "GIL", or "schema".
Connect with DigitalXNode expert interviewers for technical mock interviews, domain assessment, and enterprise job placement.