Hidden inputs in Laravel blade.php

Hey so I’m trying to sort entries by a type of pet, the code below is code from my blade.php

<div>
                        <td>
                            <form>
                                @csrf
                                <input name="cat" type="hidden" value="cat">
                                <a name="cat" href="{{ url('sorting') }}" value="cat">Cat</a>
                            </form>
                        </td>
                    </div>

In the blade file I’d have multiple links such as cat, dog, rabbit which essentially act as filtering options

I have a sort method in my controller that does the following

 public function sorting(Request $request){
        if($request->input('cat') === 'cat'){
            $pets = Pet::Where('type', 'cat')->get();
            return view('index', compact('pets'));
        }
}

In my sort method, I’m trying to check if the cat link is clicked and then if it is it would return only pets of type cat, the problem I have is that my $request->input('cat') is returning a null. How would I correct this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have multiple issues in your code:

  1. You don’t seem to have a way to actually submit the form. The link in the post won’t do it on it’s own (unless you have some event on that link in JS)
  2. <a>-tags don’t have a value-attribute and the name-attribute means something completely different for links and is not for submitting data through forms.
  3. A form without a method will use GET as default. You’re trying to retrieve the value in PHP using $request->input() which is for POST-requests. For GET requests (which uses the query string to pass data), use $request->query().

However… you don’t need the form. Just pass the value as a query parameter in the link instead:

<td>
    <a href="{{ url('sorting') }}?sort=cat">Cat</a>
</td>

Then in your PHP code, retrieve the value using:

if ($request->query('sort') === 'cat') {
    // your code
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x