Laravel includes Eloquent, an object-relational mapper (ORM) that makes database interaction straightforward. Eloquent implements the Active Record pattern.With Eloquent, each database table has a corresponding “model” class. You use the model to retrieve, insert, update, and delete records in that table.
Before using Eloquent, configure your database connection in config/database.php. By default, Laravel reads the DB_* values from your .env file.
Eloquent automatically manages created_at and updated_at columns. If you add $table->timestamps() in your migration, Eloquent sets the values automatically when you save or update a model.To disable automatic timestamp management:
class Post extends Model{ public $timestamps = false;}
Alternatively, use $guarded to specify which columns should not be mass-assignable:
class Post extends Model{ // Protect only the primary key; allow all others protected $guarded = ['id'];}
Setting $guarded to an empty array allows mass assignment for every column. If you pass user-supplied data directly, unintended columns could be overwritten. Prefer $fillable to explicitly allow only the columns you expect.
// Get published posts$publishedPosts = Post::where('published', true)->get();// Get the first matching record$post = Post::where('published', true)->first();// Find by primary key$post = Post::find(1);// Find by primary key or throw a 404$post = Post::findOrFail(1);
Here is a controller that uses the Post model to handle typical blog post operations:
<?phpnamespace App\Http\Controllers;use App\Models\Post;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\View\View;class PostController extends Controller{ // List published posts public function index(): View { $posts = Post::where('published', true) ->latest() ->get(); return view('posts.index', ['posts' => $posts]); } // Store a new post public function store(Request $request): RedirectResponse { $validated = $request->validate([ 'title' => ['required', 'string', 'max:255'], 'body' => ['required', 'string'], 'published' => ['boolean'], ]); Post::create([ ...$validated, 'user_id' => $request->user()->id, ]); return redirect('/posts'); } // Update a post public function update(Request $request, Post $post): RedirectResponse { $validated = $request->validate([ 'title' => ['required', 'string', 'max:255'], 'body' => ['required', 'string'], ]); $post->update($validated); return redirect('/posts'); } // Delete a post public function destroy(Post $post): RedirectResponse { $post->delete(); return redirect('/posts'); }}
When a controller method type-hints a model like Post $post, Laravel automatically fetches the matching record from the database based on the route parameter. This is called route model binding, and it removes the need to write Post::findOrFail($id) yourself.