CRUD Operations: Creating, Reading, Updating, and Deleting Data – Laravel Tutorial Part 4
Welcome back to our Laravel tutorial series! In Part 3, we set up our database, created database tables using migrations, and generated models in Laravel. Now, in Part 4, we’ll dive deeper into CRUD operations. CRUD stands for Create, Read, Update, and Delete, and these operations are fundamental to most web applications. By the end of this tutorial, you’ll understand how to perform CRUD operations in Laravel using Eloquent ORM.
Tutorial Part 4: CRUD Operations
Step 1: Creating Data
- To create a new record in the database, we’ll use the
create
method on our model. - Open your controller file (e.g.,
PostController.php
) and add the following code to the store method:
use App\Post;
use Illuminate\Http\Request;
public function store(Request $request)
{
$post = new Post();
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->save();
return redirect()->route('posts.index')->with('success', 'Post created successfully!');
}
Step 2: Reading Data
- To retrieve data from the database, we’ll use the
all
method to fetch all records or thefind
method to retrieve a specific record by its primary key. - Open your controller file and add the following code to the index method:
use App\Post;
public function index()
{
$posts = Post::all();
return view('posts.index', ['posts' => $posts]);
}
Step 3: Updating Data
- To update a record in the database, we’ll retrieve the record, modify its attributes, and then call the
save
method. - Open your controller file and add the following code to the update method:
use App\Post;
use Illuminate\Http\Request;
public function update(Request $request, $id)
{
$post = Post::find($id);
$post->title = $request->input('title');
$post->content = $request->input('content');
$post->save();
return redirect()->route('posts.index')->with('success', 'Post updated successfully!');
}
Step 4: Deleting Data
- To delete a record from the database, we’ll use the
delete
method. - Open your controller file and add the following code to the destroy method:
use App\Post;
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
return redirect()->route('posts.index')->with('success', 'Post deleted successfully!');
}
Conclusion: In Part 4 of our Laravel tutorial series, we’ve learned how to perform CRUD operations in Laravel using Eloquent ORM. We can now create, read, update, and delete data from our database with ease. These operations form the backbone of most web applications, and mastering them is essential for building robust and dynamic websites. In the next part of the series, we’ll explore form validation and learn how to validate user input to ensure data integrity and security. Stay tuned for Part 5!