Laravel Eloquent CRUD

CRUD operations (Create, Read, Update, Delete) in Laravel Eloquent ORM for this exact table.

posts table

id title content created_at updated_at

 Post Model (app\Models\Post.php):

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{    
    protected $fillable = ['title', 'content'];
}



CRUD Operations

Create (Insert)

Insert a new record into posts.

use App\Models\Post;

// Method 1: Using Eloquent instance
$post = new Post();
$post->title = "My First Blog";
$post->content = "This is the content of my first blog post.";
$post->save();

// Method 2: Using Mass Assignment
Post::create([
  'title' => 'Second Blog',
  'content' => 'This is another post created with mass assignment.',
]);

This will insert into posts and automatically set created_at and updated_at.

Output:posts table
id title content created_at updated_at
1 My First Blog This is the content of my first blog post. 2025-08-13 17:38:58 2025-08-13 17:38:58
2 Second Blog This is another post created with mass assignment. 2025-08-13 17:38:58 2025-08-13 17:38:58

Read (Select)

use App\Models\Post;

// Get all posts
$posts = Post::all();


// Get by ID
$post = Post::find(1);


// Get with condition
$post = Post::where('title', 'My First Blog')->first();


// Get specific columns
$posts = Post::select('id', 'title')->get();


// Paginate
$posts = Post::paginate(5);

Update

use App\Models\Post;

// Method 1: Find and update
$post = Post::find(1);
$post->title = "Updated Blog Title";
$post->content = "Updated content for the blog.";
$post->save();

// Method 2: Direct update
Post::where('id', 2)->update([
  'title' => 'Direct Update Title',
  'content' => 'Direct update content here.'
]);

This will update into posts and automatically set updated_at with current date.

Output:posts table
id title content created_at updated_at
1 Updated Blog Title Updated content for the blog. 2025-08-13 17:38:58 2025-10-13 13:35:58
2 Direct Update Title Direct update content here. 2025-08-13 17:38:58 2025-18-13 13:35:58

Delete

use App\Models\Post;

// Method 1: Find id is 1 and delete
$post = Post::find(1);
$post->delete();

// Method 2: Conditional delete
Post::where('title', 'Direct Update Title')->delete();
Output:posts table
id title content created_at updated_at

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.