fire <flash-messages /> after axios call

Viewed 34

To fire <flash-messages /> (which is inside my layout) from the controller I can do the following:

$redirect('/')->with('success', 'cart updated successfully!');

the question is how can I fire it without going to backend specially when I dealing with axois call ??

HandleInertiaRequest (Middleware)


class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            "flash" => function () use ($request) {
                return [
                    "success" => $request->session()->get("success"),
                    "error"   => $request->session()->get("error"),
                ];
            },
        ]);
    }
}

addToCart() {
     axios.post(`/api/v1/carts`, {
         name: '....',
               
     }).then(() => {
         this.$inertia.reload({
              onSuccess: page => { console.log(page) },
         })
     }).catch(() => {
          this.$inertia.reload({
              onError: errors => { console.log(errors) },
          })
     })
},

console.log result

..
.
.
flash: {success: null, error: null}

1 Answers

I solve it by access flash variable :D


addToCart() {
     axios.post(`/api/v1/carts`, {
         name: '....',
               
     }).then((res) => {
         this.$page.props.flash.success = 'Added to cart successfully'
     }).catch((err) => {
          this.$page.props.flash.error = err
     })
},
Related