menu

Questions & Answers

Redering out a view based on dropdown value in Laravel 7

I would like to render a different view for 4 dropdown values in the controller. I'm new to PHP and Laravel and just starting to understand it.

dropdown html:

 <div class="col-md-6">
 <select name="employees" class="form-control @error('employees') is-invalid @enderror">
 <option value="">-- {{ __('choose') }} --</option>
 <option value="micro">1 - 5</option>
 <option value="small">5 - 50</option>
 <option value="medium">50 - 500</option>
 <option value="large">500 +</option>
 </select>

Controller:

class RegisterControllerStep2 extends Controller
{

    public function form()
    {
        return view('auth.register_step2');
    }

    public function saveData(Request $request)
    {
        auth()->user()->update($request->only(['company_name', 'website', 'employees']));

        return redirect()->route('home');
    }
}

I want to redirect the user to another page other than home based on their selection from the employees dropdown above.

Comments:
2023-01-17 00:47:53
Would you use Jquery ?, I'm asking this because with jQuery it'd be easier to do
Answers(2) :

For giving a better experience I add this jquery function to justrusty's answer. By doing this, it is not required for the user to press submit button for changes being applied.

Add a form with an id on the select:

<form action="something" method="post">
@csrf

 <select id="employees" name="employees" class="form-control @error('employees') is-invalid @enderror">
 <option value="">-- {{ __('choose') }} --</option>
 <option value="micro">1 - 5</option>
 <option value="small">5 - 50</option>
 <option value="medium">50 - 500</option>
 <option value="large">500 +</option>
 </select>

</form>

Then add below jquery to the end of body section:

 $('#employees').change(function() {
    this.form.submit();
});

And at last, as justrusty said, redirect to the desired page in the controller:

if($request->employees==='micro'){
    return redirect()->route('micro');
}

You need something like this

public function saveData(Request $request)
{
    auth()->user()->update($request->only(['company_name', 'website', 'employees']));

    if($request->employees==='micro'){
        return redirect()->route('micro');
    }

    return redirect()->route('home');
}

Another thought I had on this is you could also do something like

return redirect()->route($request->employees);

As long as you had all your routes set up correctly with matching names to the values in your employees select