Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

luddinus's avatar

How to deal with "flash messages" when using an Api

Hi,

I'm using my Api in my web application.

For example, a form that creates a new Post.

// Api/PostsController.php
public function store()
{
   $post = Post::create(request()->all());

   return ['success' => true];
}

My first approach is to redirect to the same page with a "success" flag when the request is successful (post is created)

axios.post('api/posts', formData).then(response => {
   window.location.href = '/posts?success';
});

And then in the WebController that shows the form, show a successful message when the request has the "success" flag.

// Web/PostsController
public function create()
{
   if (request()->has('success') {
      flash('Post created successfully');
   }

   return view('posts.create');
}

Any more aproaches?

Thanks.

0 likes
8 replies
alanholmes's avatar

Hi @luddinus

If you are redirecting in the JS, you can still use your api endpoint to set a flash session, and it will still be available after the redirect.

luddinus's avatar

You sure?

All the routes of the api are using the Api middleware (no sessions), will it work?

alanholmes's avatar

Hi @luddinus

Tbh, I'm not sure, I have done it via an Ajax call, but I have a web api, that just uses the web middleware rather than the api middleware (that is a separate api for me that is not being used by a browser).

The other option, is that you pass the success message back from the api end point in the JSON, and use your JS to either show the message, or pass it along in the querystring if you are still going to redirect

deansatch's avatar

Not sure what you are doing in your blae file but I don't think the way you are setting your flash is correct. Try this:


 if (request()->has('success')) {
            request()->session()->flash('success', 'Post created successfully');
        }

and in blade view:

@if(Session::has('success'))
<p>{{ Session::get('success') }}</p>
@endif

You could actually skip the flash altogether if you are putting 'success' in the query string anyway. Just do this in blade:


@if(request()->has('success'))
<p>Post created successfully</p>
@endif

But as Alan says, the cleanest way is probably to return the message from your api and don't redirect at all. So your post api postcontroller

public function store()
{
   $post = Post::create(request()->all());

   return ['success' => true, 'message'=>'Post created successfully'];
}

And your js


axios.post('api/posts', formData).then(response => {

	if(response.success){
   		console.log(response.message); // obviously you can insert to a span or div instead
	}else{
		console.log('something went wrong'); // same^
	}	
});


Spiral's avatar

@luddinus

public function with($variableName, $variable)
    {
        $this->response['data'][$variableName] = $variable;
    }

$this->with('post', $post);
               
return response()->json('200', 'Request completed successfully!');
luddinus's avatar

@alanholmes @deansatch

I think I'm going to apply de web middleware for now (only the web application is using the api).

I prefer to redirect, it's an example, maybe I create a post and redirect to the "show page" (posts/{post_slug}) and to make something consistent for other use cases.

Thanks for the responses.

alanholmes's avatar

Hi @luddinus

If you switch to the web middleware for it, then you will be able to set the flash in your controller.

Here is an example of where I have used it:

public function store(StoreReferralRequest $request, CreateReferral $createReferral)
    {
        $referral = $createReferral->fromRequest($request);

        $request->session()->flash('referral_submitted', true);

        return response()->json([
            'success' => true,
            'redirect' => route('referrals.show', $referral)
        ], Response::HTTP_CREATED);
    }

This is getting set, and returning Json with the redirect url to the show page, and my JS does the redirect (as my form is being posted via Ajax), but once the redirect happens, I have access to the referral_submitted flash session to show a message

1 like
luddinus's avatar

Yes, same approach.

In my code I was using a global method "flash", that its a custom helper that does the same thing.

Please or to participate in this conversation.