Laravel provides a seamless way to connect with MySQL and manage database records efficiently.
In this blog post, we’ll explore how to configure database connections and implement pagination to handle large datasets smoothly.
Connecting Laravel to MySQL
To connect your Laravel application to a MySQL database, update the .env
file with your database credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password
Once updated, run the following command to clear the cache and apply changes:
php artisan config:clear
Now, Laravel is successfully connected to your MySQL database.
Creating a Model for Database Interaction
Laravel follows an MVC (Model-View-Controller) pattern, where models interact with the database. To create a model for a table, use the following Artisan command:
php artisan make:model Member
This command generates an Eloquent model named Member
, allowing you to perform database operations easily.
Using the Model in a Controller
Import the model into your controller and fetch data using:
use App\Models\Member;
public function index() {
$members = Member::all(); // Fetch all records
return view('members.index', compact('members'));
}
Implementing Pagination in Laravel
Pagination is essential when dealing with large datasets. Laravel makes it simple with the paginate()
method.
Fetching Paginated Data
Modify your controller method to use pagination:
public function index() {
$members = Member::paginate(10); // Fetch 10 records per page
return view('members.index', compact('members'));
}
Displaying Pagination in Blade Template
To display pagination links in the front-end, use:
{{ $members->links() }}
This generates beautiful paginated navigation automatically.
Querying the Database Without a Model
Although it’s recommended to use models for better code structure, you can directly query the database using Laravel’s query builder:
use Illuminate\Support\Facades\DB;
$users = DB::table('members')->get();
However, using Eloquent models ensures separation of concerns, making the code more maintainable.
Conclusion
Connecting Laravel to MySQL and implementing pagination is straightforward with Eloquent models. Using paginate()
and links()
, you can efficiently handle large datasets while keeping the UI user-friendly. Stick to Eloquent for cleaner and more structured database interactions!