Introduction
Laravel, known for its simplicity, elegance, and readability, is a popular PHP framework among developers. Pairing it with Bootstrap, the most popular CSS framework for developing responsive and mobile-first websites, can dramatically enhance your project design and frontend workflow. In this tutorial, we’ll walk through how to integrate Bootstrap into a Laravel project with a step-by-step guide.
Prerequisites
- A basic understanding of Laravel
- A local Laravel development environment
- Composer globally installed
- npm, nodejs or yarn installed
Step-by-Step Instructions
Let’s setting it up from the ground up.
Step 1: Installing Laravel
composer create-project --prefer-dist laravel/laravel your_project_name
After the installation, navigate to your project directory:
cd your_project_name
Step 2: Installing Bootstrap
Using npm or yarn, you can install Bootstrap and its dependencies:
npm install bootstrap jquery popper.js --save
or
yarn add bootstrap jquery popper.js
Bootstrap is now included in your node_modules
directory.
Step 3: Configuring Webpack
Configure Laravel Mix, Laravel’s fluent API for defining basic Webpack build steps for your application, in the webpack.mix.js
file to compile Bootstrap:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.sourceMaps();
Remember to add Bootstrap imports to your app.js
and app.scss
files to include Bootstrap JavaScript and Sass:
In app.js
require('./bootstrap');
// Import Bootstrap JavaScript
require('bootstrap');
In app.scss
// Import Bootstrap Sass
@import '~bootstrap/scss/bootstrap';
Step 4: Compiling Assets
Compile your assets using npm or yarn:
npm run dev
or
yarn run dev
This will generate compiled files in the public
directory.
Step 5: Using Bootstrap in Views
To make use of Bootstrap in your views, link to the compiled CSS and JavaScript files in your main layout file, typically resources/views/layouts/app.blade.php
:
<head>
...
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
...
<script src="{{ asset('js/app.js') }}"></script>
</body>
Advanced Usage
For advanced users, you may want to customize Bootstrap’s components or grid system by editing the Bootstrap variables in your app.scss
file before the import statement:
// Override Bootstrap's variables
$body-bg: #f8fafc;
$primary-color: #4a4a4a;
// Then import Bootstrap
@import '~bootstrap/scss/bootstrap';
This allows you to tailor Bootstrap according to your project’s design requirements.
Conclusion
Integrating Bootstrap into Laravel provides flexibility and efficiency in developing a responsive user interface. With these simple steps, you can now take advantage of Bootstrap’s vast component library and styling options within your Laravel applications.