Laravel: 0 dan Pro gacha – 4-qism: Eloquent ORM bilan ma’lumotlar bazasi

📘 Kirish

Laravel’da ma’lumotlar bazasi bilan ishlash juda soddalashtirilgan. Bunda eng asosiy vosita bu — Eloquent ORM. ORM (Object-Relational Mapping) orqali siz SQL yozmasdan turib, ma’lumotlar ustida obyektlar orqali ishlaysiz.

Bu maqolada quyidagilarni o‘rganasiz:

  • Eloquent model yaratish

  • CRUD operatsiyalar (Create, Read, Update, Delete)

  • Ma’lumotlarni olish, saqlash va o‘chirish

  • Tinker orqali test qilish


🧱 Model yaratish

Laravel’da har bir jadvalga mos model bo‘ladi. Model yaratish:

php artisan make:model Post -m

Bu ikki narsani yaratadi:

  • app/Models/Post.php (model fayli)

  • database/migrations/xxxx_create_posts_table.php (jadval migratsiyasi)


🧰 Migratsiya yozish

Misol uchun, posts jadvali:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

Keyin migratsiyani bajarish:

php artisan migrate

🧠 CRUD amallari

🔸 Ma’lumot qo‘shish

use App\Models\Post;

$post = new Post();
$post->title = 'Laravel haqida';
$post->body = 'Laravel PHP frameworki haqida maqola.';
$post->save();

Post::create([
    'title' => 'Yangi post',
    'body' => 'Bu post Eloquent orqali yaratildi.'
]);

Buning uchun Post modelida fillable aniqlanishi kerak:

protected $fillable = ['title', 'body'];

🔹 Ma’lumot olish

$posts = Post::all(); // Barcha postlar
$post = Post::find(1); // ID bo‘yicha
$post = Post::where('title', 'like', '%Laravel%')->get(); // Filter

🛠 Ma’lumotni o‘zgartirish

$post = Post::find(1);
$post->title = 'Tahrirlangan sarlavha';
$post->save();

🗑 Ma’lumotni o‘chirish

$post = Post::find(1);
$post->delete();

Yoki:

Post::destroy(1);

🧪 Artisan Tinker bilan sinash

$post = new App\Models\Post;
$post->title = 'Test post';
$post->body = 'Bu post tinker orqali yozildi.';
$post->save();

📌 Xulosa

Eloquent — Laravel’ning kuchli imkoniyatlaridan biri. U orqali siz SQL yozmasdan, model orqali to‘liq ma’lumotlar bazasi bilan ishlay olasiz.


🏁 5-qismda nimalar bo‘ladi?

5-qismdaLaravel’da formalar va validatsiya qilish haqida to‘liq ko‘rib chiqamiz. Ya’ni, foydalanuvchidan ma’lumot olish va uni tekshirish (form validation).