📜  laravel bootstrap nav active - PHP (1)

📅  最后修改于: 2023-12-03 15:02:34.617000             🧑  作者: Mango

Laravel Bootstrap Nav Active

Laravel is a popular PHP framework for web application development, and Bootstrap is a widely used HTML, CSS, and JavaScript framework for building responsive and mobile-first web pages. Bootstrap provides a variety of UI components, including navigation bars, which are essential for building user-friendly websites. In this article, we will explore how to use Bootstrap navs in Laravel and how to add the 'active' class to the current page's nav link.

Setting up Bootstrap in Laravel

First, let's set up Bootstrap in Laravel. There are different ways to do this, but we will use the Laravel Mix package to simplify the process. Laravel Mix is an NPM package that provides a fluent JavaScript API for defining Webpack build steps for your Laravel application.

  1. Install Node.js and NPM

Before we can use Laravel Mix, we need to install Node.js and NPM. To do this, go to the Node.js website and download the LTS version for your operating system. Once installed, open a terminal or command prompt and type:

node -v
npm -v

If you see output that shows the versions of Node.js and NPM, you're all set.

  1. Install Laravel Mix

Next, we need to install Laravel Mix. Open a terminal or command prompt and navigate to your Laravel project directory. Then, type:

npm install laravel-mix --save-dev

This will install Laravel Mix and save it as a development dependency in your project's package.json file.

  1. Configure Laravel Mix

Now, we need to configure Laravel Mix. In your project's root directory, create a webpack.mix.js file with the following content:

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

This tells Laravel Mix to compile your application's JavaScript and Sass files into the public/js and public/css directories, respectively.

  1. Install Bootstrap

Finally, we need to install Bootstrap. Open a terminal or command prompt and type:

npm install bootstrap --save-dev

This will install Bootstrap and save it as a development dependency in your project's package.json file.

  1. Include Bootstrap in your application

To include Bootstrap in your application, open the resources/sass/app.scss file and add the following line:

@import '~bootstrap/scss/bootstrap';

This tells Sass to import Bootstrap's SCSS files. Then, open the resources/js/bootstrap.js file and add the following lines:

window.$ = window.jQuery = require('jquery');
require('bootstrap');

This tells Laravel Mix to include jQuery and Bootstrap's JavaScript files. Finally, compile your assets by typing:

npm run dev

Now, you're ready to use Bootstrap in your Laravel application.

Using Bootstrap Navs in Laravel

Bootstrap provides various types of navigation components, including navbars, tabs, pills, and more. In this article, we will focus on the navbar component.

  1. Create a Navbar

To create a navbar in Laravel, open the resources/views/layouts/app.blade.php file and add the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title') - {{ config('app.name') }}</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item active">
                    <a class="nav-link" href="{{ url('/') }}">Home<span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{ url('/about') }}">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{ url('/contact') }}">Contact</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container">
        @yield('content')
    </div>
    <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

This code extends Laravel's default app layout and adds a navbar with three links: Home, About, and Contact. Note that we have added the active class to the Home link to indicate that it is the current page.

  1. Define Routes

To make the navbar links work, we need to define corresponding routes in Laravel. Open the routes/web.php file and add the following content:

Route::get('/', function () {
    return view('home');
});

Route::get('/about', function () {
    return view('about');
});

Route::get('/contact', function () {
    return view('contact');
});

This defines three routes that return simple views for the Home, About, and Contact pages.

  1. Create Pages

To complete the example, we need to create the three pages. Create three files resources/views/home.blade.php, resources/views/about.blade.php, and resources/views/contact.blade.php with the following content:

@extends('layouts.app')

@section('title', 'Home')

@section('content')
    <h1>Home Page</h1>
    <p>Welcome to the Home page!</p>
@endsection
@extends('layouts.app')

@section('title', 'About')

@section('content')
    <h1>About Page</h1>
    <p>Welcome to the About page!</p>
@endsection
@extends('layouts.app')

@section('title', 'Contact')

@section('content')
    <h1>Contact Page</h1>
    <p>Welcome to the Contact page!</p>
@endsection

Now, if you run your Laravel application and navigate to any of the three pages, you will see a navbar with the corresponding link highlighted.

Dynamically Adding the 'Active' Class

In the previous example, we manually added the active class to the current page's link. However, it is more convenient to do this dynamically based on the current route.

Fortunately, Laravel provides a helper function called request()->routeIs() that allows us to check if the current route matches a given pattern. We can use this function to dynamically add the active class to the navbar link that corresponds to the current route.

  1. Update Navbar Code

To dynamically add the active class, we need to update the navbar code as follows:

<ul class="navbar-nav">
    <li class="nav-item{{ request()->routeIs('home') ? ' active' : '' }}">
        <a class="nav-link" href="{{ url('/') }}">Home<span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item{{ request()->routeIs('about') ? ' active' : '' }}">
        <a class="nav-link" href="{{ url('/about') }}">About</a>
    </li>
    <li class="nav-item{{ request()->routeIs('contact') ? ' active' : '' }}">
        <a class="nav-link" href="{{ url('/contact') }}">Contact</a>
    </li>
</ul>

Here, we have added curly braces around the active class and used the ternary operator to conditionally add it based on the current route.

  1. Update Route Names

To use the routeIs() function, we need to name our routes. Update the routes/web.php file as follows:

Route::get('/', function () {
    return view('home');
})->name('home');

Route::get('/about', function () {
    return view('about');
})->name('about');

Route::get('/contact', function () {
    return view('contact');
})->name('contact');

Here, we have used the name() method to give each route a unique name.

Now, if you run your Laravel application and navigate to any of the three pages, the corresponding link in the navbar will have the active class. If you add more pages or routes, the navbar will automatically update based on the current route.

Conclusion

In this article, we have explored how to use Bootstrap navs in Laravel and how to dynamically add the 'active' class to the current page's nav link. By using Laravel Mix to set up Bootstrap, we can easily include Bootstrap's CSS and JavaScript files in our Laravel application. By using named routes and the request()->routeIs() function, we can dynamically add the 'active' class to the navbar link that corresponds to the current route.