Unable to put session in Laravel Vue using Axios

Viewed 195

I am trying to create an endpoint and send the data to then endpoint and requesting it later within the controller method. As the input value changes, it fires axios put method and pass the updated perPage data to an endpoint, I am getting a successful response, with status 200 in the console log, but the value isn't being updated or created in the sessions. I just don't know what am I missing here. Please throw some light here. Thanks!

Web

Route::put('/set-per-page', [UserController::class, 'setPerPage'])->name('set.per_page');

Controller

public function setPerPage(Request $request)
{
    $request->session()->put('perPage', $request->perPage);
    return session('perPage');
}

Component

<template>
    <input-group inline>
        <input-select v-model="perPage" placeholder="Per Page">
            <option value="5">5</option>
            <option value="10">10</option>
        </input-select>
    </input-group>
</template>

<script>
    export default {
        props: {
            perPageData: {
                type: Number
            }
        },

        data() {
            return {
                perPage: this.perPageData
            }
        },

        watch: {
            perPage: {
                handler: function() {
                    axios.put(route('set.per_page', { per_page: this.per_page })).then((response)=>{ this.$inertia.reload({ only: ['usersData'] }), console.log(response) })
                }
            }
        }
    }
</script>
2 Answers

Are you sure $request->perPage is actually set? Since no name attribute is present on the input (it's no form POST) it might be necessary to access the perPage attribute via $request->input('perPage').

The actual problem was, we cant use sessions() within public function __construct() so it was unable to get the value from the session. As per the current setup, with a minor work around the problem was solved.

Using an inline middleware, we can hook into the request's routing, so that we have full access to the session.

public function __construct()
{
    $this->middleware(function ($request, $next) {

        $this->perPage = session()->get('perPage', $this->perPage);

        return $next($request);
    });
}
Related