In plain PHP, working with a database means writing SQL strings, preparing statements, binding values and looping through results. It works, but it is a lot of repeated code. Laravel’s Eloquent lets you treat each table as a class and each row as an object. You still need to understand SQL, but you write a lot less of it by hand.
Connect to the database first
Open the .env file in your project and set your database details:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD= Recent Laravel versions default to SQLite, which is also perfectly fine for learning. Use whichever you have.
Migrations: your tables as code
Instead of creating tables by clicking around in phpMyAdmin, Laravel uses migrations. A migration is a PHP file that describes a change to the database. Because it is code, it goes into Git and everyone on the team gets the same structure.
Create a model and its migration together:
php artisan make:model Post -m Open the new file in database/migrations and describe the columns:
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->boolean('is_published')->default(false);
$table->timestamps();
});
} Run php artisan migrate and the table is created. The timestamps() call adds created_at and updated_at columns, which Eloquent fills in for you automatically.
The model
The model lives in app/Models/Post.php. By convention a model called Post maps to a table called posts, so you do not need to configure anything. You only need to say which columns can be filled in bulk:
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
protected $fillable = ['user_id', 'title', 'body', 'is_published'];
protected function casts(): array
{
return ['is_published' => 'boolean'];
}
} The fillable list matters for security. Without it, someone could add an extra field to a form, like is_admin, and if you passed the whole request into create() it would be saved. This is called a mass assignment vulnerability, and the fillable list protects you from it. Even better, pass only validated data, for example $request->validated() from a form request.
Creating, reading, updating, deleting
Here is everyday Eloquent. You will use these lines constantly:
// create
$post = Post::create([
'user_id' => auth()->id(),
'title' => 'My first post',
'body' => 'Hello world',
]);
// read
$all = Post::all();
$one = Post::find(1); // null if not found
$oneOr404 = Post::findOrFail(1); // 404 page if not found
$latest = Post::where('is_published', true)
->latest()
->take(10)
->get();
// update
$post->title = 'A better title';
$post->save();
// delete
$post->delete(); Behind the scenes, every one of these uses prepared statements, so values like the title are passed safely and SQL injection is not a worry here. Be careful only with methods that accept raw SQL, such as whereRaw() or DB::raw(). If you put user input in those, bind it with placeholders.
Relationships
Real data is connected. A user has many posts, and a post belongs to a user. You describe this once, in the models:
// in app/Models/User.php
public function posts()
{
return $this->hasMany(Post::class);
}
// in app/Models/Post.php
public function user()
{
return $this->belongsTo(User::class);
} Now you can write $user->posts to get all posts by a user, or $post->user->name to get the author’s name. Eloquent works out the foreign keys from the names, as long as you follow the conventions, like the user_id column we created earlier.
The N+1 problem
This is the most common performance mistake I see in student projects. Look at this code:
$posts = Post::all();
foreach ($posts as $post) {
echo $post->user->name;
} It looks innocent. But it runs one query to get the posts, and then one more query for every single post to get its user. Fifty posts means fifty one queries. The fix is eager loading:
$posts = Post::with('user')->get(); Now Laravel runs two queries in total, no matter how many posts there are. Get into the habit of asking “will I use a relationship inside a loop?” and add with() whenever the answer is yes. In development you can even tell Laravel to throw an error when you forget, by calling Model::preventLazyLoading() in a service provider.
Do you still need to learn SQL?
Yes, and I say this to every batch. Eloquent writes SQL for you, but when a page is slow or a query returns the wrong rows, you have to understand what it generated. You can see it by calling toSql() on a query, or by installing a debug tool like Laravel Debugbar or Telescope.
Think of Eloquent as a faster way to write queries you already understand, not as a reason to skip understanding them. Learn joins, indexes and keys in plain MySQL first, and Eloquent will feel natural instead of magical.