প্রশ্ন ১ ঃ laravel এ access token & refresh token এর পার্থক্য কি?
কখন কোথায় কোনটা বেশি ব্যবহার হয়? কিভাবে ইম্পলিমেন্ট করবো?
route এ access token ব্যবহার করবো, নাকি refresh token ব্যবহার করবো?
Answer:
Laravel-এ Access Token আর Refresh Token—দুটোর role আলাদা। ঠিকভাবে ব্যবহার করলে security + UX দুটোই ভালো হয়।
🔐 1️⃣ Access Token কী?
👉 ছোট সময়ের জন্য valid token
👉 API access করার জন্য ব্যবহার হয়
বৈশিষ্ট্য:
- ⏱️ Short lifetime (যেমন: 15 min / 1 hour)
- 🔑 প্রতিটা protected route-এ লাগে
- ⚡ Fast validation
🔄 2️⃣ Refresh Token কী?
👉 নতুন access token generate করার জন্য ব্যবহার হয়
বৈশিষ্ট্য:
- ⏱️ Long lifetime (যেমন: 7 দিন / 30 দিন)
- 🔒 বেশি secure ভাবে store করতে হয়
- ❌ Direct API access-এ ব্যবহার করা হয় না
- 🔍 Access vs Refresh Token (পার্থক্য)
🔍 Access vs Refresh Token (পার্থক্য)
| বিষয় | Access Token | Refresh Token |
|---|---|---|
| কাজ | API access | নতুন token generate |
| Lifetime | কম | বেশি |
| Security risk | বেশি (frequent use) | কম (rare use) |
| কোথায় ব্যবহার | Route/API call | Auth endpoint |
| Expire হলে | fail | নতুন access token দেয় |
🎯 3️⃣ কখন কোনটা ব্যবহার করবেন?
✅ Access Token ব্যবহার:
- সব protected API route
- যেমন:
/api/user/api/orders-
/api/profile
Authorization: Bearer access_token
✅ Refresh Token ব্যবহার:
- শুধু token renew করার সময়
POST /api/refresh-token
❗ গুরুত্বপূর্ণ প্রশ্ন:
👉 Route-এ কোনটা ব্যবহার করবো?
👉 শুধু Access Token ✅
👉 Refresh Token কখনো route protect করতে ব্যবহার করা যাবে না ❌
⚙️ 4️⃣ Laravel-এ Implementation (Simple Flow)
Laravel-এ তুমি use করতে পারো:
- Laravel Sanctum (simple API)
- Laravel Passport (OAuth2 full system)
🔥 Basic Flow
1️⃣ Login
$token = $user->createToken('api')->plainTextToken;
👉 Access token return
2️⃣ API Route Protect
Route::middleware('auth:sanctum')->get('/profile', function () {
return auth()->user();
});
🔄 Refresh Token Flow (Custom Implementation)
Sanctum defaultভাবে refresh token দেয় না
তাই manually করতে হয় 👇
Step 1: Refresh Token Table
refresh_tokens:
- id
- user_id
- token (hashed)
- expires_at
Step 2: Login Response
{
"access_token": "...",
"refresh_token": "..."
}
Step 3: Refresh API
Route::post('/refresh-token', function (Request $request) {
// validate refresh token
// issue new access token
});
🔐 5️⃣ Security Best Practices
✔ Access token short রাখো
✔ Refresh token DB-তে store করো (hashed)
✔ Refresh token revoke করতে পারো
✔ HTTPS ব্যবহার করো
✔ Token rotation ব্যবহার করো
🧠 Interview-ready Answer
Access tokens are short-lived tokens used to authenticate API requests, while refresh tokens are long-lived tokens used to generate new access tokens. In Laravel, access tokens are used in route authentication, and refresh tokens are only used in token renewal endpoints. Refresh tokens should never be used to access protected APIs.
🏁 Final Summary
👉 Access Token = API access
👉 Refresh Token = Token renew
👉 Route-এ সবসময় Access Token ✅
প্রশ্ন ২ ঃ laravel এ generator কি? কেন ব্যবহার করা হয়? কোন প্রবলেম টা সলভ করে? chunk vs generator?
Answer:
Laravel/ PHP-এ Generator বোঝা মানে তুমি memory-efficient data processing বুঝে গেছো — এটা interview-এ strong point।
🔹 1️⃣ Generator কী?
👉 Generator হলো এমন function যা একবারে সব data return না করে, ধাপে ধাপে (lazy way) data produce করে।
এটা yield keyword দিয়ে কাজ করে।
📌 Basic Example:
function numbers() {
yield 1;
yield 2;
yield 3;
}
foreach (numbers() as $num) {
echo $num;
}
👉 এখানে:
- সব data একসাথে memory-তে load হয় না
- একটার পর একটা আসে
🧠 2️⃣ কেন Generator ব্যবহার করা হয়?
👉 মূল কারণ: Memory optimization + large data handling
Problem:
$users = User::all(); // 1 million rows 😱
❌ সব data RAM-এ লোড হয়
❌ Memory crash হতে পারে
Solution (Generator):
function getUsers() {
foreach (User::cursor() as $user) {
yield $user;
}
}
✔ একবারে ১টা row memory-তে
✔ Huge data handle করা যায়
🔥 3️⃣ Generator কোন problem solve করে?
| Problem | Solution |
|---|---|
| Large dataset memory issue | Lazy loading |
| High RAM usage | Reduce memory |
| Streaming data | Real-time process |
| Long loop processing | Efficient iteration |
⚡ 4️⃣ Laravel-এ Generator কোথায় use হয়?
Laravel internally use করে:
User::cursor()
👉 এটা generator ব্যবহার করে
Example:
foreach (User::cursor() as $user) {
// process
}
✔ Memory efficient
✔ Large data safe
🔍 5️⃣ chunk vs generator (VERY IMPORTANT)
| বিষয় | chunk() | generator (cursor) |
|---|---|---|
| Memory | Medium | Very Low |
| Data load | batch (100/1000) | one by one |
| Use case | bulk processing | huge streaming |
| Speed | faster | একটু slow |
| Control | batch-based | continuous |
🔹 chunk() Example:
User::chunk(1000, function ($users) {
foreach ($users as $user) {
// process
}
});
👉 একবারে 1000 row memory-তে
🔹 cursor() Example:
foreach (User::cursor() as $user) {
// process
}
👉 একবারে ১টা row
🎯 কখন কোনটা ব্যবহার করবেন?
✅ chunk() ব্যবহার:
- Batch processing (email send, update)
Speed important
✅ generator / cursor ব্যবহার:1M+ data
Memory critical
Streaming process
🧠 Interview-ready Answer
A generator in PHP is a function that uses the
yieldkeyword to return data lazily, one item at a time, instead of loading everything into memory. It solves memory issues when working with large datasets. In Laravel,cursor()uses generators, whilechunk()processes data in batches. Generators are more memory efficient, while chunk is faster for batch operations.
🔥 Pro Insight (Impress Interviewer)
👉 তুমি বলতে পারো:
- Generator uses lazy evaluation
- Memory stays constant O(1)
- cursor() internally uses PDO cursor
- Best for large dataset streaming
প্রশ্ন ৩ ঃ laravel Model এ boot function কেন ব্যবহার করা হয়? কোন প্রবলেম টা সলভ করে? কোন সিচুয়েশনে ব্যবহার করবো?
Answer:
Laravel Model-এর boot() (এবং modern Laravel-এ booted()) হলো এমন জায়গা, যেখানে তুমি model-level global behavior একবারে define করতে পারো—যেমন events (creating/updating), global scopes, automatic field সেট করা ইত্যাদি।
🔹 1️⃣ boot() কী?
👉 Model class load হওয়ার সময় একবার run হয়
👉 এখানে তুমি model-এর events + global rules সেট করতে পারো
class Post extends Model
{
protected static function boot()
{
parent::boot();
static::creating(function ($post) {
$post->slug = strtolower(str_replace(' ', '-', $post->title));
});
}
}
✔ নতুন post create হলে auto slug generate হবে
🧠 2️⃣ কেন ব্যবহার করা হয়? (Problem it solves)
🎯 Problem:
তুমি যদি controller-এ বারবার এই logic লেখো:
$post->slug = ...
❌ Code duplicate
❌ ভুলে গেলে bug
❌ Central control নেই
✅ Solution (boot):
👉 এক জায়গায় define করো
👉 সব জায়গায় automatically apply হবে
✔ DRY (Don’t Repeat Yourself)
✔ Clean architecture
✔ Consistency
🔥 3️⃣ Common Use Cases
✅ 1. Auto Field Set করা (Very common)
static::creating(function ($model) {
$model->user_id = auth()->id();
});
✅ 2. Slug generate
static::saving(function ($model) {
$model->slug = Str::slug($model->title);
});
✅ 3. Soft restriction / validation
static::deleting(function ($model) {
if ($model->orders()->count() > 0) {
throw new Exception("Cannot delete");
}
});
✅ 4. Global Scope add করা
protected static function boot()
{
parent::boot();
static::addGlobalScope('active', function ($query) {
$query->where('status', 1);
});
}
✔ সব query-তেই auto filter
✅ 5. Audit / Logging
static::updated(function ($model) {
Log::info('Model updated', $model->toArray());
});
⚡ 4️⃣ boot() vs booted() (Important)
🔹 boot()
- Old style
-
parent::boot()call করতে হয় 🔹 booted() (Recommended)
protected static function booted()
{
static::creating(function ($model) {
$model->user_id = auth()->id();
});
}
✔ Cleaner
✔ No need parent call
🎯 5️⃣ কখন ব্যবহার করবো?
| Situation | Use boot |
|---|---|
| Same logic বারবার লাগে | ✅ |
| Model lifecycle event দরকার | ✅ |
| Auto field set | ✅ |
| Global filter | ✅ |
| Business logic centralize | ✅ |
❌ কখন ব্যবহার করবো না?
- Heavy logic ❌
- External API call ❌
- Complex business workflow ❌
👉 এগুলো Service class-এ রাখা better
🧠 Interview-ready Answer
The
boot()method in Laravel models is used to hook into model lifecycle events and define global behaviors such as auto-setting fields, applying global scopes, or handling events like creating/updating. It helps avoid code duplication and centralizes model-related logic.
🔥 Pro Insight (Impress Interviewer)
👉 তুমি বলতে পারো:
- It uses Eloquent model events
- Helps enforce data consistency
- Used for cross-cutting concerns
-
Alternative: Observer class (for cleaner architecture)
🏁 Bonus: Cleaner Way (Observer)
php artisan make:observer PostObserver
👉 বড় project হলে observer use করা better
প্রশ্ন ৪ ঃ Laravel এ queue job চালানো জন্য production এ কোন কমেন্ট চালাতে হয়? কেন চালাতে হয়? এর সাথে redis এর সম্পর্ক কি?
Answer:
Laravel এ queue job production-এ চালানোর জন্য সাধারণত তুমি artisan command manually একবার চালিয়ে থেমে যাবে না—বরং একটা long-running worker process রাখতে হয়।
🔥 1. Production এ কোন কমান্ড চালানো হয়?
সবচেয়ে কমন কমান্ড:
php artisan queue:work
Production এ সাধারণত এভাবে ব্যবহার করা হয়:
php artisan queue:work --sleep=3 --tries=3 --timeout=90
বা daemon mode (পুরানো পদ্ধতি):
php artisan queue:work --daemon
⚙️ কিন্তু আসল production setup এ এটা terminal এ চালিয়ে রাখা হয় না
Production এ সাধারণত ব্যবহার করা হয়:
✅ Supervisor (Linux process manager)
Supervisor দিয়ে worker কে background service হিসেবে চালানো হয়:
command=php /var/www/html/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
👉 কারণ:
- server restart হলে আবার auto start হবে
- crash করলে auto restart হবে
- background এ continuous run করবে
🚀 2. কেন queue worker চালাতে হয়?
Laravel queue system কাজ করে এভাবে:
১। তুমি job dispatch করো:
dispatch(new SendEmailJob());
২। job database/redis এ “pending” হিসেবে জমা হয়
৩। worker ছাড়া job কখনো execute হবে না ❌
👉 তাই queue:work চালানো মানে:
“background থেকে queue থেকে job তুলে execute করা”
⚡ 3. Redis এর সাথে এর সম্পর্ক কী?
Redis এখানে queue driver / storage + broker হিসেবে কাজ করে।
যদি তুমি Redis ব্যবহার করো:
.env:
QUEUE_CONNECTION=redis
তখন flow হবে:
Laravel App → Redis Queue → Worker (queue:work) → Job execute
🧠 Redis কেন ভালো?
Database queue এর তুলনায় Redis:
- ⚡ খুব fast (RAM based)
- 🔥 high traffic handle করতে পারে
- ⏱ low latency
- 🔁 real-time processing friendly
📦 Laravel Horizon (Redis এর জন্য best option)
Redis use করলে Laravel Horizon use করা best practice:
php artisan horizon
👉 এটা দেয়:
- queue monitoring dashboard
- auto restart workers
- performance tracking
🧾 Summary
| বিষয় | ব্যাখ্যা |
|---|---|
queue:work |
job execute করে |
| Production এ | Supervisor দিয়ে background এ চালানো হয় |
| Redis | queue data store + fast processing engine |
| সম্পর্ক | Redis queue থেকে worker job গুলো execute করে |
⚠️ Bottom line
👉 Queue শুধু “dispatch” করলে কিছুই execute হবে না
👉 Worker (queue:work) না চালালে system dead queue হয়ে থাকবে
👉 Redis শুধু storage + speed layer, worker execution engine না
প্রশ্ন ৫ ঃ laravel 9 থেকে laravel 11 এ প্রজেক্ট মাইগ্রেশানে কি কি বেষ্ট প্রাক্টিস ফলো করা উচিত? laravel documentation দেখে ব্যাখ্যা করো?
Answer:
Laravel 9 থেকে Laravel 11-এ মাইগ্রেশনের সম্পূর্ণ গাইড নিচে দেওয়া হলো, official documentation-এর উপর ভিত্তি করে:
⚠️ প্রথমে জানা দরকার: সরাসরি 9 → 11 নয়
Laravel 9 থেকে সরাসরি 11-এ আপগ্রেড করা technically সম্ভব হলেও recommended নয়। একবারে এক ভার্সন করে আগানো উচিত: 9 → 10 → 11।
✅ ধাপ ১: প্রস্তুতি (Pre-Migration)
ব্যাকআপ নাও
যেকোনো পরিবর্তনের আগে সম্পূর্ণ অ্যাপ্লিকেশন ও ডেটাবেজের ব্যাকআপ নাও। যদি কিছু ভুল হয়, আগের অবস্থায় ফেরত যেতে পারবে। Medium
PHP ভার্সন আপডেট করো
Laravel 11-এর জন্য PHP 8.2.0 বা তার বেশি প্রয়োজন। এছাড়া Laravel-এর HTTP client-এর জন্য curl 7.34.0+ লাগবে। Laravel
Third-party প্যাকেজ চেক করো
সব third-party প্যাকেজ ও dependency যাচাই করো যে সেগুলো PHP 8.2 ও Laravel 11 সাপোর্ট করে কিনা।
✅ ধাপ ২: composer.json আপডেট (High Impact)
composer.json-এ নিচের dependency-গুলো আপডেট করো:
"laravel/framework": "^11.0",
"nunomaduro/collision": "^8.1",
"laravel/sanctum": "^4.0",
"laravel/passport": "^12.0",
"laravel/cashier": "^15.0",
"laravel/telescope": "^5.0",
"laravel/breeze": "^2.0",
"livewire/livewire": "^3.4",
"inertiajs/inertia-laravel": "^1.0"
✅ ধাপ ৩: Vendor Migrations পাবলিশ করো (High Impact)
Cashier Stripe, Passport, Sanctum, Spark Stripe, ও Telescope আর নিজেদের migrations directory থেকে অটোমেটিক লোড করে না। তাই নিচের কমান্ডগুলো রান করতে হবে:
php artisan vendor:publish --tag=sanctum-migrations
php artisan vendor:publish --tag=passport-migrations
php artisan vendor:publish --tag=cashier-migrations
php artisan vendor:publish --tag=telescope-migrations
✅ ধাপ ৪: Database Migration-এর পরিবর্তন (High Impact)
Column Modify করার নিয়ম বদলেছে
কোনো column modify করার সময় এখন সব attributes explicitly লিখতে হবে। কোনো attribute বাদ গেলে সেটি drop হয়ে যাবে।
Laravel 9/10 এ কাজ করতো (এখন করবে না):
// শুধু nullable যোগ করলে unsigned ও default হারিয়ে যাবে!
$table->integer('votes')->nullable()->change();
Laravel 11-এ সঠিক উপায়:
$table->integer('votes')
->unsigned()
->default(1)
->comment('The vote count')
->nullable()
->change(); // সব attributes পুনরায় লিখতে হবে
Float/Double টাইপ বদলেছে
double ও float column type rewrite করা হয়েছে। unsignedDecimal, unsignedDouble, এবং unsignedFloat methods সরিয়ে দেওয়া হয়েছে। পরিবর্তে ->unsigned() চেইন করতে হবে।
// আগের কোড
$table->unsignedDouble('amount');
// নতুন কোড
$table->double('amount')->unsigned();
পুরনো migrations squash করো
যদি অনেক পুরনো migration থাকে, তাহলে:
php artisan schema:dump
✅ ধাপ ৫: Authentication পরিবর্তন
Password Rehashing
Laravel 11 authentication-এর সময় স্বয়ংক্রিয়ভাবে পাসওয়ার্ড rehash করবে যদি hashing algorithm-এর work factor পরিবর্তন হয়। যদি তোমার User model-এ password field-এর নাম password না হয়, তাহলে model-এ এটি specify করতে হবে:
protected $authPasswordName = 'custom_password_field';
Passport-এ Password Grant Disable
Passport 12.0-এ password grant type ডিফল্টে disabled। চালু করতে AppServiceProvider-এ লিখতে হবে:
public function boot(): void
{
Passport::enablePasswordGrant();
}
✅ ধাপ ৬: অন্যান্য গুরুত্বপূর্ণ পরিবর্তন
Carbon 3
Laravel 11, Carbon 2 ও Carbon 3 উভয়ই support করে। Carbon 3-এ diffIn* methods এখন floating-point number return করে এবং negative value-ও return করতে পারে — এটি Carbon 2 থেকে উল্লেখযোগ্য পার্থক্য।
Rate Limiting (Medium Impact)
Laravel 11-এ per-second rate limiting সাপোর্ট যুক্ত হয়েছে। Limit class constructor এখন minutes-এর বদলে seconds গ্রহণ করে। Laravel
// আগে (minutes)
new Limit($key, $attempts, 2);
// এখন (seconds)
new Limit($key, $attempts, 2 * 60);
Doctrine DBAL সরানো হয়েছে
Laravel আর doctrine/dbal package-এর উপর নির্ভরশীল নয়। পুরনো Doctrine-ভিত্তিক schema methods সরানো হয়েছে। পরিবর্তে নতুন native methods ব্যবহার করো: Schema::getTables(), Schema::getColumns(), Schema::getIndexes()।
MariaDB আলাদা Driver
Laravel 11 MariaDB-এর জন্য আলাদা dedicated driver যোগ করেছে। যদি MariaDB ব্যবহার করো, database.php config-এ driver পরিবর্তন করতে পারো। Laravel
✅ ধাপ ৭: Application Structure (মাইগ্রেশন Optional)
Laravel 11-এ নতুন simplified application structure এসেছে, কিন্তু Laravel 10 থেকে আপগ্রেড করা অ্যাপকে নতুন structure-এ migrate করার দরকার নেই। Laravel 11 পুরনো Laravel 10 structure-কেও সাপোর্ট করে।
🛠️ Bonus: Laravel Shift ব্যবহার করো
বড় codebase-এ manually আপগ্রেড করা অনেক সময়সাপেক্ষ। Laravel Shift টুলটি automatically code adjust করে, composer conflicts resolve করে এবং dependencies align করে — কয়েক ক্লিকেই Laravel 9 থেকে 11-এ যাওয়া সম্ভব হয়।
📋 Quick Checklist
| কাজ | Priority |
|---|---|
| PHP 8.2+ install | 🔴 High |
composer.json আপডেট |
🔴 High |
| Vendor migrations publish | 🔴 High |
| Column modify migrations ঠিক করা | 🔴 High |
| Float/Double type আপডেট | 🔴 High |
| Carbon 3 compatibility চেক | 🟡 Medium |
| Rate Limiter seconds-এ রাখঞ্জর | 🟡 Medium |
| Passport password grant চেক | 🟡 Medium |
| Doctrine DBAL লোড replace | 🟢 Low |
সবচেয়ে নিরাপদ পথ হলো staging environment-এ আগে সব পরীক্ষা করো, তারপর production-এ deploy করো।
প্রশ্ন ৬ ঃ laravel এ clouser কি? কেন ব্যবহার করা হয়? কোন প্রবলেম টা সলভ করে?
Php তে clouser & magic method কি?
Answer:
Laravel-এ Closure কী?
Closure হলো anonymous function (নামহীন ফাংশন) যেটাকে variable-এ store করা যায়, argument হিসেবে pass করা যায়, বা return করা যায়।
PHP-তে Closure হলো Closure class-এর একটি instance।
// সাধারণ named function
function add($a, $b) {
return $a + $b;
}
// Closure (anonymous function)
$add = function($a, $b) {
return $a + $b;
};
echo $add(2, 3); // 5
কেন Closure ব্যবহার করা হয়?
১. Route Definition-এ
// ছোট logic-এর জন্য আলাদা Controller না বানিয়ে
Route::get('/hello', function () {
return 'Hello World';
});
Route::get('/user/{id}', function ($id) {
return User::find($id);
});
২. Collection-এ (সবচেয়ে বেশি ব্যবহার)
$users = collect([
['name' => 'Rahim', 'age' => 25],
['name' => 'Karim', 'age' => 17],
['name' => 'Salam', 'age' => 30],
]);
// filter() - closure দিয়ে condition
$adults = $users->filter(function ($user) {
return $user['age'] >= 18;
});
// map() - closure দিয়ে transform
$names = $users->map(function ($user) {
return strtoupper($user['name']);
});
৩. use keyword দিয়ে বাইরের variable ধরা
এটা Closure-এর সবচেয়ে গুরুত্বপূর্ণ feature।
$discount = 10;
$getPrice = function($price) use ($discount) {
return $price - $discount;
};
echo $getPrice(100); // 90
echo $getPrice(200); // 190
useছাড়া Closure বাইরের variable দেখতে পায় না।
৪. Middleware-এ
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(function ($request, $next) {
if (!auth()->check()) {
return redirect('/login');
}
return $next($request);
});
৫. Event & Queue-এ
Event::listen('user.registered', function ($user) {
Mail::to($user->email)->send(new WelcomeMail($user));
});
৬. Service Container Binding-এ
// AppServiceProvider
$this->app->bind('PaymentGateway', function ($app) {
return new StripeGateway(config('services.stripe.key'));
});
৭. Query Scope-এ (Eager Loading)
$users = User::with(['posts' => function ($query) {
$query->where('published', true)
->orderBy('created_at', 'desc');
}])->get();
কোন Problem Solve করে?
সমস্যা ১: ছোট কাজের জন্য আলাদা ফাংশন বানানো waste
// ❌ এভাবে প্রতিটার জন্য আলাদা ফাংশন বানানো অনেক verbose
function filterAdults($user) { return $user['age'] >= 18; }
function filterSeniors($user) { return $user['age'] >= 60; }
// ✅ Closure দিয়ে inline-এই লেখা যায়
$adults = $users->filter(fn($u) => $u['age'] >= 18);
$seniors = $users->filter(fn($u) => $u['age'] >= 60);
সমস্যা ২: Context/State ধরে রাখা
$tax = 0.15;
$shipping = 50;
// Closure-এ দুটো বাইরের variable একসাথে ব্যবহার
$totalPrice = function($price) use ($tax, $shipping) {
return ($price * (1 + $tax)) + $shipping;
};
echo $totalPrice(1000); // 1200
সমস্যা ৩: Lazy Evaluation (দরকার হলে তবেই execute)
// Closure পাস করলে সাথে সাথে execute হয় না
// যখন দরকার তখন call করা হয়
$this->app->bind('HeavyService', function () {
// শুধুমাত্র এই service যখন resolve হবে তখনই চলবে
return new HeavyService();
});
Arrow Function (PHP 7.4+) — Closure-এর Short Syntax
// পুরনো Closure
$multiply = function($n) use ($factor) {
return $n * $factor;
};
// Arrow Function - use ছাড়াই বাইরের variable পায়
$factor = 3;
$multiply = fn($n) => $n * $factor;
// Collection-এ
$doubled = $users->map(fn($u) => $u['age'] * 2);
Interview-এ Summary বলার মতো করে
"Closure হলো anonymous function যেটা variable-এ রাখা যায় এবং argument হিসেবে পাস করা যায়। Laravel-এ এটা Route, Collection, Service Container, Event, Queue সহ প্রায় সব জায়গায় ব্যবহার হয়। এটা মূলত তিনটা সমস্যা সমাধান করে — ১) ছোট one-time logic-এর জন্য আলাদা function না বানিয়ে inline লেখা, ২) use keyword দিয়ে বাইরের context/state ধরে রাখা, এবং ৩) Lazy evaluation — মানে code তখনই execute হয় যখন দরকার।"
দুইটা টপিকই PHP-তে খুব গুরুত্বপূর্ণ 👍
আমি সহজভাবে Closure আর Magic Method—দুটোই উদাহরণসহ বুঝিয়ে দিচ্ছি।
🔹 1️⃣ PHP Closure কী?
👉 Closure (Anonymous Function) হলো এমন একটি function যার কোনো নাম নেই, এবং এটাকে variable-এ assign করে ব্যবহার করা যায়।
📌 Basic Example:
$greet = function($name) {
return "Hello, $name";
};
echo $greet("Ruhul");
🔥 Closure এর বিশেষ ক্ষমতা (use keyword)
👉 বাইরের variable ভিতরে ব্যবহার করা যায়
$message = "Hi";
$greet = function($name) use ($message) {
return "$message, $name";
};
echo $greet("Sujon");
✔ use ($message) না দিলে কাজ করবে না
🚀 Laravel-এ Closure Example:
Route::get('/', function () {
return "Welcome";
});
👉 এখানে route-এর ভিতরের function টা closure
🎯 Closure কেন ব্যবহার করি?
- Callback function
- Route handling
- Collection method (map, filter)
- Clean & short code
🔹 2️⃣ PHP Magic Method কী?
👉 Magic Method হলো special method, যেগুলো automatically call হয় নির্দিষ্ট situation-এ।
👉 সব magic method শুরু হয় __ (double underscore) দিয়ে
🔥 Common Magic Methods
1️⃣ __construct() (Constructor)
class User {
public function __construct() {
echo "Object created";
}
}
👉 Object create হলে auto call হয়
2️⃣ __destruct()
public function __destruct() {
echo "Object destroyed";
}
3️⃣ __get() (Undefined property access)
class User {
public function __get($name) {
return "Property $name not found";
}
}
$user = new User();
echo $user->email;
4️⃣ __set() (Undefined property set)
public function __set($name, $value) {
echo "Setting $name = $value";
}
5️⃣ __call() (Undefined method call)
public function __call($method, $args) {
echo "Method $method not found";
}
6️⃣ __toString()
public function __toString() {
return "User object";
}
👉 Object print করলে call হয়
7️⃣ __invoke()
class Test {
public function __invoke() {
return "Called as function";
}
}
$obj = new Test();
echo $obj(); // invoke
🔍 Closure vs Magic Method
| বিষয় | Closure | Magic Method |
|---|---|---|
| কী | Anonymous function | Special class method |
| কাজ | Callback / inline logic | Auto-trigger behavior |
| Scope | Function level | Class level |
| Laravel usage | Route, Collection | Model, Eloquent |
🧠 Interview-ready Answer
👉 Closure:
Closure is an anonymous function that can capture variables from its parent scope using the
usekeyword.
👉 Magic Method:
Magic methods are special methods in PHP that are automatically invoked when certain actions occur, such as object creation, property access, or method calls.
🔥 Pro Insight (Impress Interviewer)
- Laravel heavily uses closures (route, middleware, collections)
- Eloquent uses magic methods (
__get,__set) for dynamic properties
প্রশ্ন ৭ ঃ আমার কাছে তো access token আছেই, তাহলে আবার কেন refresh token লাগবে? laravel এর sanctum token দিয়ে উদাহরণসহ বুঝিয়ে দাও।
Answer:
🧠 Short Core Idea
👉 Access token short-lived
👉 Refresh token long-lived
👉 Access token compromise হলে damage কম রাখতে short রাখা হয়
👉 Refresh token দিয়ে নতুন access token নেওয়া যায় (user আবার login না করে)
🔥 Problem Without Refresh Token
ধরা যাক তুমি শুধু access token ব্যবহার করছো:
Access Token Expire → User logout → আবার login করতে হবে ❌
👉 Bad UX
👉 Mobile app / SPA-তে annoying
✅ Solution With Refresh Token
Access Token Expire
↓
Refresh Token দিয়ে নতুন Access Token
↓
User stays logged in ✅
🔐 Security Reason (Most Important)
👉 যদি access token 7 দিনের জন্য দাও:
- Token leak হলে attacker 7 দিন access পাবে 😱
👉 তাই best practice:
- Access token → 15 min / 1 hour
- Refresh token → long-lived (7–30 days)
✔ Risk minimize
✔ User experience maintain
⚙️ Laravel Sanctum দিয়ে Example
👉 Laravel Sanctum defaultভাবে refresh token দেয় না
👉 তাই আমরা custom implementation করি
🧩 Step 1: Login API
public function login(Request $request)
{
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
// Access Token
$accessToken = $user->createToken('api')->plainTextToken;
// Refresh Token (custom)
$refreshToken = Str::random(60);
DB::table('refresh_tokens')->insert([
'user_id' => $user->id,
'token' => hash('sha256', $refreshToken),
'expires_at' => now()->addDays(7),
]);
return response()->json([
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
]);
}
🔄 Step 2: Refresh Token API
public function refresh(Request $request)
{
$token = DB::table('refresh_tokens')
->where('token', hash('sha256', $request->refresh_token))
->where('expires_at', '>', now())
->first();
if (! $token) {
return response()->json(['error' => 'Invalid refresh token'], 401);
}
$user = User::find($token->user_id);
// New Access Token
$newAccessToken = $user->createToken('api')->plainTextToken;
return response()->json([
'access_token' => $newAccessToken
]);
}
🔐 Step 3: Protected Route
Route::middleware('auth:sanctum')->get('/profile', function () {
return auth()->user();
});
👉 এখানে শুধু access token ব্যবহার হবে ✅
❗ Important Rule
| জায়গা | কোন token |
|---|---|
| API route | ✅ Access Token |
| Refresh endpoint | ✅ Refresh Token |
| Protected resource | ❌ Refresh Token না |
🧠 Interview-Ready Answer
Access tokens are short-lived for security, so even if they are compromised, the damage is limited. Refresh tokens are used to generate new access tokens without forcing the user to log in again, improving user experience. In Laravel Sanctum, access tokens are used to protect routes, while refresh tokens are implemented separately for token renewal.
🔥 Pro Insight (Impress Interviewer)
👉 তুমি এটা বললে interviewer impressed হবে:
- Token rotation use করা উচিত
- Refresh token revoke করা উচিত logout-এ
- Store refresh token hashed (password এর মতো)
- Access token stateless, refresh token stateful
🏁 One-line Killer Answer
👉
“Access token is for access, refresh token is for continuity.”
প্রশ্ন ৮ ঃ lockForupdate() vs sharedLock() in laravel? explain with proper example. describe the situation when i need to use lockForupdate() or sharedLock()?
Answer:
Laravel-এ lockForUpdate() এবং sharedLock()—দুটাই database row-level locking-এর জন্য ব্যবহার করা হয় (pessimistic locking), যাতে concurrent request-এ data inconsistency না হয়।
🔹 lockForUpdate() (Write Lock)
👉 এটা exclusive lock দেয়
- অন্য কোনো transaction read বা write করতে পারবে না (
wait করবে) - সাধারণত update করার আগে use করা হয়
- অবশ্যই transaction-এর ভিতরে ব্যবহার করতে হয়
Example:
DB::transaction(function () {
$user = User::where('id', 1)
->lockForUpdate()
->first();
$user->balance -= 100;
$user->save();
});
🧠 Use Case:
👉 যখন critical update করছো (যেমন: balance deduct, stock update)
🔹 sharedLock() (Read Lock)
👉 এটা shared/read lock দেয়
- অন্যরা read করতে পারবে
- কিন্তু কেউ update করতে পারবে না (wait করবে)
Example:
DB::transaction(function () {
$user = User::where('id', 1)
->sharedLock()
->first();
// safe read operation
});
🧠 Use Case:
👉 যখন data read করছো এবং ensure করতে চাও যে read করার সময় কেউ modify না করে
🔥 Key Difference:
| Feature | lockForUpdate() | sharedLock() |
|---|---|---|
| Lock Type | Exclusive (Write) | Shared (Read) |
| Read Allowed | ❌ না | ✅ হ্যাঁ |
| Write Allowed | ❌ না | ❌ না |
| Use Case | Update করার আগে | Consistent read |
⚠️ Important Notes:
- দুটোই
DB::transaction()এর ভিতরে ব্যবহার করতে হবে - MySQL InnoDB engine হলে ভালোভাবে কাজ করে
- Deadlock avoid করতে consistent order maintain করা দরকার
🎯 Short Interview Version:
"lockForUpdate() applies an exclusive lock for write operations, preventing other reads and writes until the transaction completes. sharedLock() applies a read lock, allowing other reads but blocking writes. We use lockForUpdate() for critical updates like balance changes, and sharedLock() for consistent reads without modification."
প্রশ্ন 9 ঃ public function productCharacteristics(Request $request) , এখানে Request টা কি? কেন ব্যবহার করা হয়? কোন প্রবলেমটা সলভ করে?
Answer:
🔹 Request কী?
Laravel-এ Request হলো Illuminate\Http\Request class-এর একটি instance,
যেটা current HTTP request-এর সব data (input, query, headers, files, cookies) represent করে।
🔹 কেন ব্যবহার করা হয়?
👉 Controller method-এ Request $request দিলে Laravel automatically Dependency Injection দিয়ে object inject করে।
এর মাধ্যমে তুমি সহজে access করতে পারো:
- Form data →
$request->input('name') - Query param →
$request->query('page') - File →
$request->file('image') - Header →
$request->header('Authorization')
🔹 Example:
public function productCharacteristics(Request $request)
{
$name = $request->input('name');
$price = $request->input('price');
return response()->json([
'name' => $name,
'price' => $price
]);
}
🔥 এটা কোন problem solve করে?
❌ Without Request (Raw PHP)
$name = $_POST['name'];
👉 সমস্যা:
- Unstructured data access
- Validation কঠিন
- Test করা কঠিন
- Security risk (sanitize manually করতে হয়)
✅ With Request (Laravel way)
👉 Solve করে:
- ✔️ Clean & structured data access
- ✔️ Built-in validation support
- ✔️ Dependency Injection (testable code)
- ✔️ Security (sanitization, filtering support)
🔹 Advanced (Impress করার জন্য)
👉 Custom Form Request ব্যবহার করলে validation আলাদা করা যায়:
php artisan make:request ProductRequest
public function productCharacteristics(ProductRequest $request)
{
// already validated
}
🎯 Short Interview Version:
"Request is an instance of Laravel’s HTTP request class that contains all incoming request data. It is injected via dependency injection and provides a clean, secure, and structured way to access input, headers, and files, solving problems like unstructured data handling and manual validation."
প্রশ্ন 10 ঃ notification class এ toArray() কেন ব্যবহার করা হয়? কোন প্রবলেমটা সলভ করে? laravel এ উদাহরণসহ দেখাও।
Answer:
🔹 toArray() কী?
Laravel-এর Notification class-এ toArray() method ব্যবহার করা হয়
👉 notification data-কে array format-এ convert করার জন্য, বিশেষ করে যখন database channel ব্যবহার করা হয়।
🔹 কেন ব্যবহার করা হয়?
যখন তুমি notification database-এ store করো, তখন Laravel একটা JSON column (data) এ data save করে।
👉 toArray() সেই data structure define করে।
🔥 এটা কোন problem solve করে?
👉 Without toArray():
- কী data store হবে, clear না
- inconsistent structure হতে পারে
- frontend/API-তে ব্যবহার করা কঠিন
👉 With toArray():
- ✔️ Structured data storage
- ✔️ Consistent format
- ✔️ সহজে API / UI-তে use করা যায়
🔹 Laravel Example
Step 1: Notification তৈরি
php artisan make:notification OrderPlaced
Step 2: Notification class
use Illuminate\Notifications\Notification;
class OrderPlaced extends Notification
{
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'order_id' => 101,
'message' => 'Your order has been placed successfully',
'amount' => 500,
];
}
}
Step 3: Trigger Notification
$user->notify(new OrderPlaced());
🔹 Database-এ কী save হবে?
notifications table:
{
"order_id": 101,
"message": "Your order has been placed successfully",
"amount": 500
}
🔹 কোথায় ব্যবহার হয়?
- Database notification
- Broadcast (real-time notification)
- API response হিসেবে reuse করা যায়
🧠 Insight (Impress করার জন্য)
👉 toArray() = data contract for notification
✔️ Backend → Frontend communication clean করে
✔️ Future change easy হয় (single place control)
🎯 Short Interview Version:
"
toArray()in Laravel notifications defines the data structure that will be stored in the database or sent via channels like broadcast. It ensures consistent, structured data storage and solves the problem of unstructured or inconsistent notification payloads."
প্রশ্ন 11 ঃ laravel এ psr কি? কেন ব্যবহার করা হয়? কোন প্রবলেমটা সলভ করে? laravel এ উদাহরণসহ দেখাও।
Answer:
🔹 PSR কী?
PSR (PHP Standards Recommendation) হলো PHP-এর coding standard ও interface guideline, যেটা তৈরি করে PHP-FIG।
👉 এর উদ্দেশ্য: বিভিন্ন PHP project ও framework-এর মধ্যে consistency ও interoperability নিশ্চিত করা।
🔹 Laravel-এ PSR কোথায় ব্যবহার হয়?
Laravel internally অনেক PSR follow করে, যেমন:
- PSR-4 → class autoloading
- PSR-7 → HTTP message structure (indirect support)
- PSR-12 → coding style
🔥 কেন ব্যবহার করা হয়?
👉 PSR solve করে:
- ❌ Different coding style problem
- ❌ Library compatibility issue
- ❌ Team collaboration complexity
👉 ✔️ Benefits:
- Consistent code structure
- Easy to understand & maintain
- Framework/library integration সহজ
🔹 Laravel Example (PSR-4 Autoloading)
👉 ধরো তুমি একটা class বানাও:
namespace App\Services;
class PaymentService {
public function pay() {
return "Paid";
}
}
👉 PSR-4 অনুযায়ী:
- Namespace →
App\Services - Folder →
app/Services/PaymentService.php
👉 Laravel automatically autoload করবে (manual require দরকার নেই)
🔹 Real Usage in Controller
use App\Services\PaymentService;
class PaymentController extends Controller
{
public function pay(PaymentService $service)
{
return $service->pay();
}
}
👉 এখানে:
- Autoload হচ্ছে PSR-4 অনুযায়ী
- Clean DI possible হচ্ছে
🧠 Insight (Impress করার জন্য)
👉 PSR = "common language for PHP developers"
✔️ Laravel, Symfony, Composer—সব একই standard follow করে
✔️ তাই ecosystem powerful
🎯 Short Interview Version:
"PSR (PHP Standards Recommendation) is a set of coding and interface standards defined by PHP-FIG to ensure consistency and interoperability across PHP projects. Laravel follows standards like PSR-4 for autoloading, which allows classes to be automatically loaded based on their namespace, solving issues like inconsistent structure and manual file inclusion."
প্রশ্ন 12 ঃ laravel এ artisan কি? artisan folder এর কাজ কি ও কি কি থাকে এই ফোল্ডারে ? কেন ব্যবহার করা হয়? কোন প্রবলেমটা সলভ করে? laravel এ উদাহরণসহ দেখাও।
Answer:
🔹 Artisan কী?
Laravel-এ Artisan হলো built-in CLI (Command Line Interface) tool
👉 যেটার মাধ্যমে আমরা command চালিয়ে project manage করতে পারি
🔹 “artisan folder” আসলে কী?
👉 এখানে একটু clarify করা জরুরি:
Laravel-এ আলাদা কোনো “artisan folder” নেই ❌
✔️ artisan হলো project root-এ থাকা একটি single PHP file
👉 এটা CLI entry point হিসেবে কাজ করে
🔹 artisan file-এর কাজ কী?
- Laravel application bootstrapping করে
- Console kernel (
app/Console/Kernel.php) load করে - সব command register ও execute করে
🔹 কোথায় কী থাকে?
📁 artisan (root file)
#!/usr/bin/env php
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
👉 entry point for CLI
📁 app/Console/Kernel.php
- সব Artisan command register হয়
- scheduling define করা যায়
📁 app/Console/Commands/
- Custom command class থাকে
🔥 কেন ব্যবহার করা হয়?
👉 Artisan solve করে:
- ❌ repetitive manual কাজ
- ❌ file structure create করতে সময় লাগে
- ❌ automation নাই
👉 ✔️ Benefits:
- Fast development
- Automation (task scheduling)
- Clean project structure
🔹 Common Commands Example
php artisan make:controller UserController
php artisan make:model Product -m
php artisan migrate
php artisan serve
🔹 Custom Command Example
php artisan make:command SendEmails
class SendEmails extends Command
{
protected $signature = 'email:send';
public function handle()
{
$this->info('Emails sent successfully!');
}
}
👉 Run:
php artisan email:send
🧠 Insight (Impress করার জন্য)
👉 Artisan = Laravel-এর automation engine
✔️ Code generation + task automation + scheduling
✔️ Developer productivity অনেক বাড়ায়
🎯 Short Interview Version:
"Artisan is Laravel’s command-line interface used for automating tasks like code generation, migrations, and scheduling. The
artisanfile in the project root acts as the CLI entry point, while commands are registered in the Console Kernel. It solves repetitive manual work and improves developer productivity."
প্রশ্ন 13 ঃ laravel এ throughput কি? কেন ব্যবহার করা হয়? কোন প্রবলেমটা সলভ করে? laravel এ উদাহরণসহ দেখাও।
Answer:
🔹 Throughput কী?
Throughput মানে হলো—একটা system (Laravel app) নির্দিষ্ট সময়ে কতগুলো request handle করতে পারে।
👉 সহজভাবে:
“এক সেকেন্ডে কতগুলো request process করতে পারি”
🔹 কেন গুরুত্বপূর্ণ?
👉 High throughput মানে:
- বেশি user handle করতে পারবে
- performance ভালো
- server efficiently কাজ করবে
🔥 এটা কোন problem solve করে?
👉 Without optimization:
- ❌ server slow হয়ে যায়
- ❌ request queue জমে যায়
- ❌ timeout / crash হতে পারে
👉 ✔️ Throughput improve করলে:
- Fast response
- High scalability
- Better user experience
🔹 Laravel-এ Throughput কিভাবে improve করি?
1. Caching
$users = Cache::remember('users', 60, function () {
return User::all();
});
2. Queue ব্যবহার করা
dispatch(new SendEmailJob($user));
👉 heavy task async হয়ে যায় → main request fast
3. Eager Loading (N+1 problem solve)
$posts = Post::with('comments')->get();
4. Database Optimization
- indexing
- pagination
User::paginate(10);
5. Rate Limiting
Route::middleware('throttle:60,1')->group(function () {
Route::get('/api', fn() => 'ok');
});
🔹 Simple Example (Before vs After)
❌ Without Queue:
Mail::to($user)->send(new WelcomeMail());
👉 request slow
✅ With Queue:
Mail::to($user)->queue(new WelcomeMail());
👉 fast response → throughput increase
🧠 Insight (Impress করার জন্য)
👉 Throughput ≠ Response Time
- Response Time → ১টা request কত দ্রুত
- Throughput → মোট কতগুলো request handle করা যায়
🎯 Short Interview Version:
"Throughput refers to how many requests a Laravel application can handle within a given time. It is important for scalability and performance. We improve throughput using caching, queues, database optimization, and rate limiting, which helps handle more users efficiently and prevents slowdowns or crashes."
প্রশ্ন 14 ঃ $title = ProductCharacteristicsTitle::where('domain_id',$domain?->id)->first();, এখানে ?-> ও :: টা কি? কেন ব্যবহার করা হয়? কোন প্রবলেমটা সলভ করে? -> vs ?-> vs optional() ?
Answer:
🔹 :: (Scope Resolution Operator)
👉 PHP-তে :: ব্যবহার করা হয় static access এর জন্য
ProductCharacteristicsTitle::where(...)
✔️ এখানে:
-
where()method staticভাবে call হচ্ছে - Laravel-এ এটা আসলে Eloquent Model-এর মাধ্যমে query builder start করে
👉 Use cases:
- Static method call
- Constant access
- Model query শুরু করা
🔹 ?-> (Nullsafe Operator)
👉 PHP 8+ feature
👉 Object null হলে error না দিয়ে safely null return করে
$domain?->id
✔️ মানে:
-
$domainযদি null হয় → error দিবে না - result হবে
null
🔥 এটা কোন problem solve করে?
👉 Without ?->:
$domain->id
❌ যদি $domain = null হয় → Fatal Error
👉 With ?->:
$domain?->id
✔️ Safe → no crash
🔹 -> vs ?-> vs optional()
| বিষয় | -> |
?-> |
optional() |
|---|---|---|---|
| Null safe? | ❌ না | ✅ হ্যাঁ | ✅ হ্যাঁ |
| PHP version | সব | PHP 8+ | Laravel helper |
| Syntax | simple | clean | একটু verbose |
| Return | error দিতে পারে | null return | null return |
🔹 Example Comparison
❌ Normal (->)
$domain->id; // crash if null
✅ Nullsafe (?->)
$domain?->id;
✅ optional()
optional($domain)->id;
🔹 Real Example (Laravel)
$title = ProductCharacteristicsTitle::where(
'domain_id',
$domain?->id
)->first();
👉 এখানে:
-
::→ model থেকে query start -?->→$domainnull হলেও safe
🧠 Insight (Impress করার জন্য)
👉 ?-> = modern PHP way
👉 optional() = Laravel legacy/helper way
✔️ নতুন project-এ ?-> prefer করা হয় (clean & native)
🎯 Short Interview Version:
"
::is the scope resolution operator used for static access, like starting an Eloquent query.?->is the nullsafe operator that prevents errors when accessing properties on a null object by returning null instead. Compared to->, which can throw errors, both?->and Laravel’soptional()helper provide safe null handling, with?->being the modern PHP approach."
প্রশ্ন 15 ঃ design pattern কী? কয়েকটা design pattern এর নাম উদাহরণসহ বলো? কেন ব্যবহার করা হয়? কোন প্রবলেমটা সলভ করে? laravel এ উদাহরণসহ দেখাও।
Answer:
🔹 Design Pattern কী?
Design Pattern হলো software development-এর জন্য proven reusable solution, যা সাধারণ recurring problem solve করতে সাহায্য করে।
👉 এটা কোনো code না, বরং problem solving template।
🔥
কেন ব্যবহার করা হয়?
👉 Design pattern solve করে:
- ❌ messy / unstructured code
- ❌ tight coupling
- ❌ hard to maintain system
- ❌ scalability issue
👉 ✔️ Benefits:
- Clean architecture
- Reusable code
- Easy testing
- Maintainable system
🔹 Common Design Patterns (Laravel context)
1️⃣ Singleton Pattern
👉 নিশ্চিত করে একটি class-এর only one instance তৈরি হয়
Laravel Example:
DB::connection();
👉 Laravel internally database connection singleton হিসেবে manage করে
2️⃣ Factory Pattern
👉 object creation logic hide করে
Example:
$user = User::factory()->create();
👉 Laravel Model Factory use করে testing/data generation
3️⃣ Repository Pattern
👉 database logic আলাদা layer-এ রাখা
Example:
class UserRepository {
public function all() {
return User::all();
}
}
👉 Controller:
public function index(UserRepository $repo) {
return $repo->all();
}
4️⃣ Observer Pattern
👉 event trigger হলে automatic action
Laravel Example:
User::created(function ($user) {
Mail::to($user->email)->send(new WelcomeMail());
});
5️⃣ Strategy Pattern
👉 runtime অনুযায়ী behavior change করা
Example:
interface PaymentStrategy {
public function pay($amount);
}
👉 Stripe / PayPal interchangeable
🔥 Laravel Real Example (Combined Pattern)
👉 ধরো e-commerce system:
Repository + Service Pattern
class OrderRepository {
public function create($data) {
return Order::create($data);
}
}
class OrderService {
public function __construct(
protected OrderRepository $repo
) {}
public function placeOrder($data) {
return $this->repo->create($data);
}
}
👉 Controller:
public function store(OrderService $service)
{
return $service->placeOrder(request()->all());
}
🧠 Problem Solve Summary
| Problem | Design Pattern |
|---|---|
| Duplicate code | Factory |
| Tight coupling | Repository |
| Complex logic scattering | Service Pattern |
| Multiple behavior handling | Strategy |
| Automatic event handling | Observer |
| Multiple instances issue | Singleton |
🎯 Short Interview Version:
"Design patterns are reusable solutions to common software design problems. They solve issues like tight coupling, code duplication, and maintainability. Common patterns include Singleton (single instance), Factory (object creation), Repository (data abstraction), Observer (event handling), and Strategy (dynamic behavior). In Laravel, we use these patterns to build scalable and clean architecture, such as repositories for database abstraction and observers for model events."
প্রশ্ন 16 ঃ RBAS vs ABAC? & related with policy & gate?
Answer:
🔥 Authentication vs Authorization
প্রথমে এটা clear করা দরকার।
| *Term * | Meaning |
|---|---|
| Authentication | তুমি কে? |
| Authorization | তুমি কী করতে পারবে? |
🔥 RBAC (Role-Based Access Control)
👉 User-এর role অনুযায়ী permission দেওয়া হয়।
Example
| User | Role |
|---|---|
| Rahim | Admin |
| Karim | Editor |
| Sakib | Customer |
Permission Example
| Role | Permission |
|---|---|
| Admin | সব করতে পারবে |
| Editor | edit করতে পারবে |
| Customer | শুধু view |
Laravel Example
if(auth()->user()->role === 'admin') {
// allow
}
Real Example
Admin → create/update/delete
Editor → update
User → read only
🔥 ABAC (Attribute-Based Access Control)
👉 Role না, বিভিন্ন attribute/condition অনুযায়ী access control হয়।
Attributes হতে পারে
- user age
- department
- location
- ownership
- time
- subscription plan
Example
User can edit post
ONLY IF:
- user_id matches
- AND post status = draft
- AND within 24 hours
Laravel Example
if (
$user->id === $post->user_id &&
$post->status === 'draft'
) {
// allow
}
🔥 RBAC vs ABAC Difference
| RBAC | ABAC |
|---|---|
| Role based | Attribute based |
| Simple | Flexible |
| Easy manage | Complex logic |
| Static permission | Dynamic permission |
🔥 When Use RBAC?
যখন:
- system simple
- fixed roles আছে
Example:
- admin panel
- CMS
- school management
🔥 When Use ABAC?
যখন:
- complex business rules
- dynamic permission
- ownership based access
Example:
- banking
- SaaS
- enterprise system
🔥 Laravel Gate
Gate হলো simple authorization system।
Usually:
- small logic
- quick permission check
Gate Example
AppServiceProvider
Gate::define('edit-post', function ($user, $post) {
return $user->id === $post->user_id;
});
Use
if (Gate::allows('edit-post', $post)) {
// allow
}
🧠 Gate = simple permission check
🔥 Laravel Policy
Policy হলো model-based authorization class।
Large project এ বেশি use হয়।
Create Policy
php artisan make:policy PostPolicy
Example
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
Use in Controller
$this->authorize('update', $post);
🔥 Gate vs Policy
| Gate | Policy |
|---|---|
| Small/simple logic | Large/model logic |
| Closure based | Class based |
| Quick checks | Organized authorization |
🔥 RBAC with Gate Example
Gate::define('admin-access', function ($user) {
return $user->role === 'admin';
});
🔥 ABAC with Policy Example
public function update(User $user, Post $post)
{
return
$user->department_id === $post->department_id
&&
$post->status === 'draft';
}
🎯 Real Interview Answer
RBAC
Access control based on user roles.
ABAC
Access control based on attributes and conditions.
Gate
Simple authorization mechanism in Laravel.
Policy
Organized model-based authorization class in Laravel.
🚀 Easy Memory Trick
RBAC = ROLE
ABAC = ATTRIBUTE
Gate = Small
Policy = Large
Q : Design a Laravel Authorization System Architecture (RBAC + ABAC + Policy + Gate + Middleware + Cache Optimization)
Answer:
🏗️ Laravel Authorization System Architecture (Enterprise Level)
🔷 1. High-Level Architecture Flow
Request
↓
Middleware (Auth + Role Check)
↓
Gate (Global Permission Layer)
↓
Policy (Resource-Level ABAC Rules)
↓
Service Layer (Business Logic)
↓
Cache Layer (Permission Optimization)
↓
Database (RBAC + Attributes)
🔐 2. RBAC Layer (Role-Based Access Control)
Role Based Access Control (RBAC)
🎯 Purpose:
- Basic access control
- User role define করে permission decide করা
🧱 DB Design
- users
- roles
- permissions
- role_user
- permission_role
🔹 Middleware Example
Route::middleware(['role:admin'])->group(function () {
Route::get('/admin', AdminController::class);
});
🔥 Cached Role Check
Cache::remember("user_role_{$user->id}", 3600, function () use ($user) {
return $user->roles->pluck('name');
});
⚡ 3. Gate Layer (Global Permission Check)
Laravel Gate
🎯 Purpose:
- Simple global rules
- RBAC shortcut
🔹 Example
Gate::define('access-dashboard', function ($user) {
return in_array('admin', $user->roles->pluck('name')->toArray());
});
🔹 Usage
if (Gate::allows('access-dashboard')) {
// allow
}
🧠 4. Policy Layer (ABAC Engine)
Laravel Policy
🎯 Purpose:
👉 Resource-based + attribute-based control (ABAC)
🔥 Example (Product Policy)
class ProductPolicy
{
public function update(User $user, Product $product)
{
return $user->id === $product->seller_id
&& $product->status !== 'locked'
&& $user->is_active;
}
}
🔥 Register Policy
protected $policies = [
Product::class => ProductPolicy::class,
];
🔹 Usage
$this->authorize('update', $product);
⚡ 5. Middleware Layer (First Line Defense)
🎯 Purpose:
- Request filtering before controller
- Fast rejection (performance optimization)
class CheckRole
{
public function handle($request, Closure $next, $role)
{
if (!$request->user()->hasRole($role)) {
abort(403);
}
return $next($request);
}
}
🧠 6. ABAC Layer (Advanced Rules Engine)
Attribute Based Access Control (ABAC)
🎯 Decision based on:
- User attributes
- Resource attributes
- Environment context
🔥 Example
return $user->department === $product->department
&& $user->location === 'BD'
&& now()->hour < 18;
⚡ 7. Cache Optimization Layer (VERY IMPORTANT)
🎯 Problem:
Every request → DB hit for roles/permissions ❌
🔥 Solution: Permission Cache
Cache::remember("permissions_{$user->id}", 3600, function () use ($user) {
return $user->roles()
->with('permissions')
->get()
->pluck('permissions')
->flatten()
->pluck('name');
});
🔥 Middleware Cache Usage
if (!Cache::get("permissions_{$user->id}")->contains($permission)) {
abort(403);
}
🚀 Full System Flow (Real Request)
User Request
↓
Auth Middleware
↓
Role Middleware (RBAC)
↓
Gate Check (global permission)
↓
Policy Check (ABAC rules)
↓
Service Layer execution
↓
Cache used for permission lookup
↓
Response
⚡ Why This Architecture Works
✔ Scalability
- RBAC → simple filtering
ABAC → fine-grained control
✔ PerformanceCache reduces DB load
Middleware short-circuits request
✔ SecurityMulti-layer defense
Least privilege principle
✔ MaintainabilitySeparation of concerns
Clean architecture
🧠 Senior-Level Insight
👉 Real systems (banking / SaaS / ERP):
✔ RBAC = baseline access
✔ ABAC = contextual restriction
✔ Policy = resource logic
✔ Gate = quick checks
✔ Middleware = early rejection
✔ Cache = performance booster
🚨 Common Mistakes (Interview Warning)
❌ Only using roles for everything
❌ No caching → DB overload
❌ Business logic inside controller instead of policy
❌ Mixing RBAC + ABAC logic in one place
🎯 Interview Answer (English)
"A scalable Laravel authorization system combines RBAC for role-based access control and ABAC for attribute-based fine-grained rules. RBAC is implemented using roles and permissions, while ABAC is handled through policies that evaluate user, resource, and contextual attributes. Gates provide global authorization shortcuts, and middleware acts as the first layer of request filtering. For performance, permissions are cached using Laravel Cache to reduce database load and improve response time."
🎯 Interview Answer (Bangla)
"একটি scalable Laravel authorization system-এ RBAC ব্যবহার করা হয় role-based access control এর জন্য এবং ABAC ব্যবহার করা হয় fine-grained contextual rules এর জন্য। RBAC roles ও permissions দিয়ে implement করা হয়, আর ABAC policies দিয়ে user, resource এবং context অনুযায়ী decision নেওয়া হয়। Gates global permission check করে, middleware request filter করে, এবং performance বাড়ানোর জন্য cache ব্যবহার করা হয় যাতে বারবার database hit না লাগে।"
প্রশ্ন 17 ঃ Database Selection (কখন কোনটা ব্যবহার করবেন)?
Answer:
✅ Database Selection — When to use what?
👉 Core idea:
“It depends on consistency, scalability, query pattern, and data structure.”
🧠 1. SQL Databases (MySQL / PostgreSQL)
- MySQL
- PostgreSQL
🔹 When to use:
- Structured data
- Strong relationships
- ACID transactions needed
- Financial systems
💡 Real Use Case (Laravel)
👉 E-commerce system
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->decimal('total');
$table->timestamps();
});
Order::with('items', 'user')->where('user_id', $id)->get();
👉 Why SQL?
- Order + payment consistency must be correct
- JOIN operations needed
- Transaction required
DB::transaction(function () {
Order::create($data);
Payment::create($payment);
});
⚡ 2. NoSQL (MongoDB)
MongoDB
🔹 When to use:
- Flexible schema
- Rapidly changing data
- High scale applications
- Log / content / feed system
💡 Laravel Example (MongoDB use case)
👉 Blog / CMS system where fields change frequently
Post::create([
'title' => 'Laravel Tips',
'meta' => [
'views' => 100,
'tags' => ['php', 'laravel']
]
]);
👉 Why NoSQL?
- No fixed schema needed
- Fast write/read at scale
- Nested JSON structure natural
🚀 3. In-Memory Database (Redis)
Redis
🔹 When to use:
- Cache
- Session storage
- Rate limiting
- Real-time data
💡 Laravel Example
Cache:
Cache::remember('users', 60, function () {
return User::all();
});
Session:
SESSION_DRIVER=redis
Rate Limiting:
Route::middleware('throttle:60,1')->group(function () {
Route::get('/api/data', fn() => 'ok');
});
👉 Why Redis?
- Microsecond response
- Reduces DB load
- Scales API performance
🧠 4. Vector Database (AI / GenAI)
Pinecone
🔹 When to use:
- AI search (semantic search)
- ChatGPT-like systems
- Recommendation engine
💡 Laravel Example (AI Search System)
👉 Product search:
$embedding = OpenAI::embeddings($query);
$results = Product::vectorSearch($embedding)->get();
👉 Use case:
- “Best running shoes” → semantic match
- Not keyword-based search
🌐 5. Graph Database
Neo4j
🔹 When to use:
- Social network
- Relationship-heavy system
- Recommendation engine
💡 Use Case Example
👉 Friend system:
- User A → friend → User B → friend → User C
A → B → C relationship traversal
👉 Query:
- “Friends of friends”
SQL-এ expensive, Graph DB-তে fast
🔥 Real Architecture Example (Laravel System)
👉 Imagine a large SaaS platform
| Layer | Database |
|---|---|
| Users, Orders, Payments | MySQL (SQL) |
| Product search / logs | MongoDB |
| Cache / sessions | Redis |
| AI recommendation | Vector DB |
| Social features | Graph DB |
🧠 Key Thinking Principle (VERY IMPORTANT)
👉 You don’t choose database based on popularity
👉 You choose based on:
- Consistency (ACID vs eventual)
- Speed (latency)
- Scalability
- Query complexity
🎯 Short Interview Version (English)
"Database selection depends on the use case. SQL databases like MySQL or PostgreSQL are used for structured data and transactions such as e-commerce or banking systems. NoSQL databases like MongoDB are used for flexible schema and high scalability. Redis is used for caching, sessions, and fast in-memory operations. Vector databases are used for AI-based semantic search, while graph databases are used for relationship-heavy data like social networks. The key decision depends on consistency, scalability, and query patterns."
🎯 Short Interview Version (Bangla)
"Database নির্বাচন পুরোপুরি use-case এর উপর নির্ভর করে। Structured data এবং transaction-heavy system যেমন e-commerce বা banking এর জন্য SQL (MySQL/PostgreSQL) ব্যবহার করা হয়। Flexible schema এবং high scalability এর জন্য NoSQL (MongoDB) ভালো। Cache, session এবং fast performance এর জন্য Redis ব্যবহার করা হয়। AI বা semantic search এর জন্য Vector DB, আর social network বা relationship-heavy data এর জন্য Graph DB ব্যবহার করা হয়। মূল সিদ্ধান্ত নির্ভর করে consistency, scalability এবং query pattern এর উপর।"
প্রশ্ন 18 ঃ ১৬ কোটি ইউজারকে SMS পাঠানো (System Design)?
Answer:
🚀 Problem: ১৬ কোটি ইউজারকে SMS পাঠানো
👉 Requirement:
- 160M users
- Time-bound campaign (e.g. 1–2 hours)
- Reliable delivery
- Retry if failed
- Avoid SMS gateway overload
❌ Wrong Approach (What NOT to say)
Redis Queue only:
- Redis queue single-node bottleneck
- Memory pressure
- Not ideal for huge streaming workload
- No strong durability for massive event stream
✅ Correct High-Level Architecture
🧠 Core Idea:
👉 “Event Streaming + Distributed Workers + Batch Processing”
🔥 Recommended Stack
1️⃣ Message Streaming Layer
Apache Kafka
👉 Why Kafka?
- Handles millions of events/sec
- Persistent log-based system
- Horizontal scaling (partitioning)
- Fault tolerant
2️⃣ Queue Workers
RabbitMQ (alternative)
👉 Consumers process messages in parallel
3️⃣ SMS Gateway Pool
- Twilio / local gateways / multiple providers
- Load balancing
4️⃣ Laravel Backend
- Producer → sends jobs to Kafka
- Consumer workers → process SMS sending
🧱 Architecture Flow
Admin Panel (Laravel)
↓
Campaign API
↓
Kafka Topic (sms_campaign)
↓
Partitioned Consumers (Workers)
↓
Batch Processor (1000 users per batch)
↓
SMS Gateway Pool
↓
Retry Queue (failed SMS)
🚀 Laravel Implementation (Real Example)
🔹 1. Producer (Laravel)
foreach ($users as $user) {
Kafka::publish('sms_campaign', [
'phone' => $user->phone,
'message' => $message
]);
}
🔹 2. Consumer Worker
class SmsConsumer
{
public function handle($message)
{
try {
SmsService::send(
$message['phone'],
$message['message']
);
} catch (\Exception $e) {
RetryQueue::push($message);
}
}
}
🔹 3. Batch Processing (Optimization)
collect($messages)
->chunk(1000)
->each(function ($batch) {
dispatch(new SendSmsBatchJob($batch));
});
🔹 4. Queue Job (Laravel)
class SendSmsBatchJob implements ShouldQueue
{
public function handle()
{
foreach ($this->batch as $data) {
SmsGateway::send($data['phone'], $data['message']);
}
}
}
🔹 5. Rate Limiting per Gateway
RateLimiter::attempt(
'sms-gateway',
1000,
function () {
// send SMS
}
);
⚡ Why This Architecture Works
✔ Scalability
- Kafka partitions → horizontal scaling
Multiple consumers
✔ ReliabilityRetry queue
Dead letter queue (DLQ)
✔ Fault toleranceIf gateway fails → fallback gateway
✔ PerformanceBatch sending reduces API calls
🧠 Key Design Thinking
👉 You are NOT sending SMS directly
👉 You are building a distributed event pipeline
⚡ Comparison (Redis vs Kafka)
| Feature | Redis Queue | Kafka |
|---|---|---|
| Scale | Medium | Massive |
| Persistence | Low | High |
| Throughput | Moderate | Very High |
| Use case | Small apps | Enterprise systems |
🎯 Short Interview Version (English)
"For sending SMS to 160 million users, a simple queue like Redis is not sufficient. A scalable architecture would use a distributed event streaming system like Apache Kafka to handle message ingestion. The system would partition messages, and multiple consumer workers would process them in batches. Each worker sends SMS via a pool of SMS gateways with retry and rate-limiting mechanisms. This ensures high throughput, fault tolerance, and horizontal scalability."
🎯 Short Interview Version (Bangla)
"১৬ কোটি ইউজারকে SMS পাঠানোর জন্য Redis queue যথেষ্ট না। এর জন্য Apache Kafka এর মতো distributed event streaming system ব্যবহার করতে হয়, যেখানে message partition করে multiple worker parallel ভাবে process করে। প্রতিটি worker batch আকারে SMS gateway ব্যবহার করে message পাঠায়, এবং failure হলে retry system কাজ করে। এতে system scalable, fast এবং fault-tolerant হয়।"
🔥 Final Interview Insight (Very Important)
👉 Interviewer এখানে এটা দেখতে চায়:
- তুমি Redis-এ আটকে না থেকে scalable thinking করো কিনা
- distributed system বুঝো কিনা
- real-world architecture design করতে পারো কিনা
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.