Use same method for inertia response and json response Laravel Jetstream



PHP Snippet 1:

public function index()
{
    $users = User::active()
        ->orderByName()
        ->get(['id', 'name', 'email']);

    if (request()->wantsJson()) {
        return $users;
    }

    return Inertia::render('Users', [
        'users' => $users
    ]);
}

PHP Snippet 2:

<script>
import { usePage } from '@inertiajs/inertia-vue3';

const { version } = usePage();

export default {
    name: 'Users',
    props: {
        users: Object,
    },
    data() {
        return {
            userObj: [],
            loading: false,
        };
    },
    methods: {
        customReload() {
            this.loading = true;

            this.axios.get('/users', {
                headers: {
                    'X-Inertia': true,
                    'X-Inertia-Partial-Component': 'Users',
                    'X-Inertia-Partial-Data': 'users',
                    'X-Inertia-Version': version.value,
                }
            }).then(({data}) => {
                console.log(data.props.users);
                this.userObj = data.props.users;
            })
            .catch(console.error)
            .then(() => {
                this.loading = false;
            });
        },
    },
};
</script>

PHP Snippet 3:

<script>
export default {
    name: 'Users',
    props: {
        users: Object,
    },
    data() {
        return {
            loading: false,
        };
    },
    methods: {
        partialReload() {
            this.loading = true;
            this.$inertia.reload({
                only: ['users'],
                onSuccess() {
                    // Print new props!
                    console.log(this.users);
                },
                onBefore(PendingVisit) {},
                onError(Errors) {},
                onStart() {},
                onProgress() {},
                onComplete() {},
                onAbort() {},
                onCancel() {},
                onFinish(ActiveVisit) {
                    this.loading = false;
                },
            });
        },
    },
};
</script>