bootstrap Tabs in foreach laravel not working
To use Bootstrap Tabs in a Laravel foreach
loop, follow these steps:
- First, make sure you have installed Bootstrap and Laravel via Composer. If you haven't, install them using the following commands:
composer require laravel/ui
npm install && npm run dev
- Create a new Blade template file or modify an existing one where you want to use the Bootstrap Tabs within the
foreach
loop.
@extends('layouts.app')
@section('content')
<div class="container">
<ul class="nav nav-tabs" id="myTab">
@foreach ($data as $item)
<li class="nav-item">
<a class="nav-link @if($loop->first) active @endif" data-toggle="tab" href="#{{ $item->id }}" role="tab" aria-controls="{{ $item->id }}">{{ $item->name }}</a>
</li>
@endforeach
</ul>
<div class="tab-content">
@foreach ($data as $item)
<div class="tab-pane @if($loop->first) active @endif" id="{{ $item->id }}">
{{ $item->content }}
</div>
@endforeach
</div>
</div>
@endsection
-
In the above example,
$data
is an array or collection containing the data for each tab. Each item in the array should have anid
andname
property, and an optionalcontent
property. -
The
@if($loop->first)
condition is used to set the active tab for the first iteration of the loop. -
Make sure your JavaScript and CSS files are being loaded correctly. You can use the following line at the bottom of your
<head>
tag to load Bootstrap CSS:
<link rel="stylesheet" href="https://stack.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
And this line at the bottom of your <body>
tag to load Bootstrap JS:
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stack.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
With these steps, you should be able to use Bootstrap Tabs within a Laravel foreach
loop.