0

I tried a couple of things to display an error message. The idea is that the user can add tags to his products. On my main view is a table with all products listed. Every line of the table have his own a checkbox and the user can select any product he want, to add some tags to these products on the next page.

My problem is, I want to display a flash message that tells the user, he haven't checked any checkboxes. Nothing more then that. Currently he gets directed to the next page with no product selected.


My tries

Thats the controller function, the user getting directed to, if he submits the form.

public function edit() {

// some non important controller code 
if(count(Input::get('id')) == 0)
{
    Session::flash('danger', 'Sie haben kein Produkt gewählt!');
    return redirect()->back();
}
else
{
    return view('layout.edit.productedit', [
        'ids' => $data,                  // non important variables
        'products' => $product_name        
    ]);
}

}

and in my view:

@if (Session::has('danger'))
    <div class="alert alert-danger">{{ Session::get('danger') }}</div>
@endif

That didn't worked so well. The user gets his error message displayed but if he does everything right, the next page also gets this error message AND the tagging request doesn't work anymore.

So I need another way to check if the user has selected any checkbox and tell him, he need's to select at least a single checkbox to continue adding tags.

Maybe with a Javascript/Jquery solution or another way in laravel.

Thanks for taking your time and I'm sorry for my bad english.

1 Answer 1

2

Instead of manually validate the input like that, I would use validate() method,

public function edit(Request $request, $id)
{
    $this->validate($request, [
        'title'      => 'required|string'
        'mycheckbox' => 'accepted'
    ]);

    // if user passes the validation above, the code here will be executed
    // Otherwise user will be redirected back to previous view with old input and validation errors.
    return view('my-view');
}

In your view you can get the error like this:

@if (session()->has('title'))
    <div class="alert alert-danger">{{ session()->first('mycheckbox') }}  </div>
@endif

@if (session()->has('mycheckbox'))
    <div class="alert alert-danger">{{ session()->first('mycheckbox') }}  </div>
@endif

Read the official documentation and myanswer to see another examples.

Sign up to request clarification or add additional context in comments.

2 Comments

what is title in this case?
That just an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.