to get you to the next step, you just need to pass $data to the view correctly
return view('test', compact('data'));
then, look into view composers. This is a technique to pass data into every view
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I read the forum showing how to hard coding to add active css in the view, for example
<div class="{{ @if ($var == "Book") active @endif }}">Book</div>
<div class="{{ @if ($var == "Game") active @endif }}">Game</div>
<div class="{{ @if ($var == "Music") active @endif }}">Music</div>
but how about dynamic get data from database to make the navbar/sidebar ? ok, i skip all the html code just make a simple page
// route
Route::get('/types/{current_id}', 'TypesController@index');
the database table called 'site_types' actived = 0 means in maintenance, so will hide from the navbar/sidebar
| id | name | actived |
| --- | --- | --- |
| 1 | Books | 1 |
| 2 | Game | 0 |
| 3 | Music | 1 |
// controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class TypesController extends Controller
{
public function index($current_id)
{
$data['current_id'] = $current_id;
$data['types'] = DB::table('site_types')->where('actived', 1)->get();
return view('test', $data);
}
}
i followed Jeffrey Way - Laravel 5.4 From Scratch: Layouts and Structure https://laracasts.com/series/laravel-from-scratch-2017/episodes/10
views/test.blade.php
@extends ('layouts.master')
@section ('content')
this is test content
@endsection
views/layouts/master.blade.php
<body>
@include ('layouts.navbar')
@yield ('content')
</body>
views/layouts/navbar.blade.php
@foreach ($data['types'] as $type)
{{ $type->id }} {{ $type->name }} @if ($type->id == $data['current_id']) (css is active) @endif<br>
@endforeach
when i access the link below got an error Undefined variable: data
localhost.dev/types/1
localhost.dev/types/3
because the $date is not Global ?
if yes, how to set it to Global ?
and how to make the navbar/sidebar load on every page ?
Thanks
Yes you can pass an array of data. In the view you just use the array elements and not the array itself.
So, in your original code, in the view;
@foreach ($types as $type)
{{ $type->id }} {{ $type->name }} @if ($type->id == $current_id)
(css is active) @endif<br>
@endforeach
Please or to participate in this conversation.