How to keep checkbox checked during pagination in laravel?

Member

by kadin , in category: PHP Frameworks , 5 months ago

How to keep checkbox checked during pagination in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 5 months ago

@kadin 

To keep a checkbox checked during pagination in Laravel, you can store the state of the checkbox in the session or pass the checkbox state along with the pagination data to the view.


Here is an example of how you can achieve this:

  1. Store checkbox state in session:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// In your controller method
public function index(Request $request)
{
    if($request->has('checkbox')) {
        session()->put('checkbox_state', true);
    } else {
        session()->forget('checkbox_state');
    }

    $items = Item::paginate(10);
    return view('index', compact('items'));
}


Then, in your view, you can check the session value to determine whether the checkbox is checked or not:

1
<input type="checkbox" name="checkbox" {{ session('checkbox_state') ? 'checked' : '' }}>


  1. Pass checkbox state along with pagination data:
1
2
3
4
5
6
7
8
// In your controller method
public function index(Request $request)
{
    $items = Item::paginate(10);
    $checkboxState = $request->has('checkbox') ? true : false;
    
    return view('index', compact('items', 'checkboxState'));
}


In the view, you can then check the $checkboxState variable to determine whether the checkbox is checked or not:

1
<input type="checkbox" name="checkbox" {{ $checkboxState ? 'checked' : '' }}>


By using either of these methods, the checkbox state will persist across pagination in Laravel.