To create new records in the database, use the create()
method or the save()
method on a model.
Example (Using create()
):
Post::create([
'title' => 'My First Post',
'content' => 'This is the content of my first post.',
]);
Example (Using save()
):
$post = new Post;
$post->title = 'My First Post';
$post->content = 'This is the content of my first post.';
$post->save();
Note: For mass assignment protection, ensure the $fillable
property is set in the model to allow specific fields to be mass-assigned.
$posts = Post::all();
Laravel provides several methods to retrieve data from the database. You can use methods like all()
, find()
, where()
, and first()
to read records.
Example (Using all()
to get all records):
$post = Post::find(1); // Get post with ID = 1
Example (Using where()
for conditions):
$posts = Post::where('title', 'like', '%Laravel%')->get();
To update an existing record, first retrieve the model instance, modify its attributes, and then save the changes.
Example (Updating a single record):
$post = Post::find(1); // Find post with ID 1
$post->title = 'Updated Title';
$post->content = 'Updated content';
$post->save();
To delete records, you can use the delete()
method on a model instance or query.
Example (Using delete()
on an instance):
$post = Post::find(1); // Find post with ID 1
$post->delete();
Example (Using delete()
on a query):
Post::where('title', 'like', '%Laravel%')->delete();
Laravel also supports soft deletes, which allow you to mark records as deleted without actually removing them from the database. To enable this feature, add the SoftDeletes
trait in your model.
Example (Soft Deletes):
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
CRUD operations are fundamental to web development, and Laravel makes handling them simple through its Eloquent ORM. By following these steps, you can easily create, read, update, and delete data in your Laravel applications. Whether you need to work with single records or collections, Laravel’s Eloquent provides a straightforward way to manage your database operations.