When building web applications, you constantly need to read from and write to a database. In traditional programming, this means writing raw SQL queries. But in Laravel, there is a much friendlier, object-oriented way: Eloquent Models.
What is an Eloquent Model?
Think of an Eloquent Model as a bilingual translator sitting between your PHP code and your database tables. Instead of thinking about rows, columns, and SQL syntax, you treat every record as a familiar PHP object. For example, if you have a database table named posts, Laravel gives you a corresponding Post model class.
Creating a Model with Artisan
Laravel makes creating a model effortless through the Artisan command line tool. Open your terminal in your project root and run:
# Create a new Eloquent Model for posts
php artisan make:model PostLaravel automatically places your new model file inside the app/Models/Post.php directory. By default, it looks like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
// Laravel automatically maps this class to the 'posts' table!
}Fetching and Saving Data Simply
With your Model ready, interacting with data feels completely natural. Look how readable and clean these operations are:
// 1. Fetch all posts from the database
$allPosts = Post::all();
// 2. Find a specific post by its ID (e.g., ID = 1)
$post = Post::find(1);
// 3. Create a brand new record
$newPost = new Post();
$newPost->title = 'My First Blog Post';
$newPost->content = 'Laravel Eloquent makes coding fun!';
$newPost->save(); // Saves directly to the database!Notice that you did not write a single line of SELECT * FROM or INSERT INTO. Eloquent handles all the complex SQL behind the scenes safely, preventing common security bugs like SQL injection.
3 Things to Remember
- One Model equals One Table: By convention, a singular model name (like
PostorUser) automatically connects to the plural table (postsorusers). - Simple Methods Replace Raw SQL: Friendly methods like
::all(),::find(), and->save()keep your code readable and expressive. - Built-in Safety: Eloquent uses parameterized queries automatically, protecting your application from malicious input without extra effort.