skip to Main Content

I have created a dropdown list using Laravel. Now I want this list to show on multiple pages. Like a Login.blade and register.blade.

Controller:

class DropDownController extends Controller
{
    public function dropdownlist()
    {

        $rolls['roll'] = roll::get(["roll_id", "roll"]);
        return view('auth.register', $rolls);   
        // return view('auth.login', $rolls);
    }
   
}

Route:

Route::get('register',[DropDownController::class,'dropdownlist']);

Login Blade:

<div class="form-group">
                    <label>Users</label>
                    <select name="roll">
                        <option value="" selected disabled>Select Users</option>
                        @foreach($roll as $row)
                        <option value="{{$row->roll_id}}">{{$row->roll}}</option>
                        @endforeach
                    </select>
                    <span class="text-danger">
                        @error('roll')
                        {{ $message }}
                        @enderror
                    </span>
                </div>

Now I want this list to show on multiple pages. Like a Login.blade and register.blade.

2

Answers


  1. To show a dropdown list in multiple view blades using Laravel, you can use every function like that-

    $rolls=roll::select('roll_id','roll')->get();
    return view('auth.register', $rolls); 
    

    and also use in login controller-

    $rolls=roll::select('roll_id','roll')->get();
    return view('auth.login', $rolls); 
    

    now use this variable then show in pages
    and if you try this then create global function in user model and use anywhere

    <div class="form-group">
                        <label>Users</label>
                        <select name="roll">
                            <option value="" selected disabled>Select Users</option>
                            @foreach($rolls as $row)
                            <option value="{{$row->roll_id}}">{{$row->roll}}</option>
                            @endforeach
                        </select>
                        <span class="text-danger">
                            @error('rolls')
                            {{ $message }}
                            @enderror
                        </span>
                    </div>
    
    Login or Signup to reply.
  2. If i’m understanding correctly you would be best to create your dropdown as a component and using a view composer to pass the required variables into it.

    Some documentation of view composers:
    https://laravel.com/docs/10.x/views#view-composers

    within the pages you require the dropdown you can either use @include('dropdown-menu') or <x-dropdown-menu />

    Using the view composer will allow you to pass the variables into the component view that you define.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search