📘 Eloquent Models & Relationships
  
🔹 1. What is Eloquent?
  Eloquent is Laravel’s ORM that connects PHP classes to database tables.
  📦 2. Creating a Model
  php artisan make:model Product
  📄 3. Basic Model Structure
  class Product extends Model {
    protected $fillable = ['name', 'price'];
}
  
  🧠 4. Retrieving Data
  Product::all();
Product::find(1);
Product::where('name', 'Pen')->get();
  
  ✏️ 5. Inserting Data
  $product = new Product;
$product->name = 'Pen';
$product->price = 100;
$product->save();
Product::create(['name' => 'Book', 'price' => 200]);
  
  🧽 6. Updating Data
  $product = Product::find(1);
$product->price = 150;
$product->save();
  
  ❌ 7. Deleting Data
  $product = Product::find(1);
$product->delete();
Product::destroy(1);
  
  🔗 8. Relationships
  
    
      | Type | 
      Methods | 
    
    
      | One to One | 
      hasOne / belongsTo | 
    
    
      | One to Many | 
      hasMany / belongsTo | 
    
    
      | Many to Many | 
      belongsToMany | 
    
  
  🧩 One-to-One
  // User.php
public function profile() {
    return $this->hasOne(Profile::class);
}
  
  👨👩👧 One-to-Many
  // Post.php
public function comments() {
    return $this->hasMany(Comment::class);
}
  
  🔄 Many-to-Many
  // Student.php
public function courses() {
    return $this->belongsToMany(Course::class);
}
  
  ✅ Summary Table
  
    
      | Task | 
      Code | 
    
    
      | Create Model | 
      php artisan make:model Product | 
    
    
      | Insert | 
      Product::create([...]) | 
    
    
      | Update | 
      $product->save() | 
    
    
      | Delete | 
      Product::destroy(1) | 
    
    
      | All Records | 
      Product::all() | 
    
  
 
0 Comments