What are Contracts in Laravel
In Laravel, Contracts are basically interfaces that define what a class should do, without specifying how it does it.
🔹 Simple Meaning
A Contract = Promise (Interface)
It tells:
“Any class implementing me must provide these methods.”
🔧 Why Laravel Uses Contracts
Laravel uses contracts to:
- Keep code clean and flexible
- Allow easy swapping of implementations
- Support Dependency Injection
- Improve testability
🧠 Example
Laravel provides a contract like:
Illuminate\Contracts\Cache\Repository
This contract defines methods like:
get($key);
put($key, $value, $minutes);
Now different cache systems (file, database, Redis) can implement this contract.
💡 Real Example in Code
use Illuminate\Contracts\Cache\Repository as Cache;
class UserController
{
protected $cache;
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
public function index()
{
return $this->cache->get('users');
}
}
👉 Here:
- You're using a contract, not a specific cache class.
- Laravel automatically injects the correct implementation.
🔁 Contract vs Facade
| Feature | Contract | Facade |
|---|---|---|
| Type | Interface | Static-like class |
| Flexibility | High | Moderate |
| Testing | Easy (mockable) | Harder |
| Example | Cache Contract | Cache::get() |
🎯 Common Laravel Contracts
-
Illuminate\Contracts\Auth\Authenticatable -
Illuminate\Contracts\Queue\Queue -
Illuminate\Contracts\Mail\Mailer -
Illuminate\Contracts\Filesystem\Filesystem
🧩 In Short
Contracts in Laravel = Interfaces that define behavior, enabling flexible and maintainable code using Dependency Injection.