user10139010
user10139010

Reputation:

Laravel select field validation

I am currently building a feature where a user can select an option from a select box, once an item is selected you can click a button which hits my endpoint which submits and stores it.

However if i dont select anything but then click the button it just hits a 404 page on the same endpoint.

Blade

Below contains the blade syntax for the select box and button.

<div class="row align-items-center">
    <div class="col-md">
        <small class="text-success">
            please select one of the teams below to store your preference.
        </small>
        {!! Form::open(['route' => ['team.create.link', $team->id],'method' => 'post', 'class' => 'needs-validation','novalidate', null]) !!}
        {!! Form::select('teams[]', $teams, '', ['class' => 'custom-select', 'multiple'], ['required']) !!}
        <button class="btn btn-primary btn-sm mt-3 float-right">
            <i class="fas fa-fw fa-plus-circle mr-2"></i>
            Add</button>
        {!! Form::close() !!}
    </div>
</div>

Method

Below is the method used for storing the new input within the pivot table.

public function link(string $teamId)
{
    $team= Team::findOrFail($teamId);

    $links = Input::get('teams');

    $link = Team::findOrFail($links);

    $team->links()->attach($link);

    session()->flash('success', 'Link Added.');

    return back();
}

Help

How would i modify this so that the button cant be clicked and returns a required error if an option isnt selected? i've tried adding ['required'] to the form::select but i had no luck with that.

Can anyone push me in the right direction?

Upvotes: 0

Views: 174

Answers (1)

julianstark999
julianstark999

Reputation: 3616

You can validate your Reqeust with $this->validate

use Illuminate\Http\Request;

public function link(Request $reqeust, string $teamId)
{
    $request->validate([
        'teams' => 'required',
    ]);

    $team = Team::findOrFail($teamId);

    $links = Input::get('teams');

    $link = Team::findOrFail($links);

    $team->links()->attach($link);

    session()->flash('success', 'Link Added.');

    return back();
}

Take a look at the official Laravel Documentation for Validation

Upvotes: 0

Related Questions