jpeterson579's avatar

Laravel Api post request redirect back to external url

Hi all!

I am trying to create an API that allows me to make a contact form on another site and then send a post request to my API URL that stores the info in a database and generates an email.

The problem I am having is that when the person submits the form, they go to the api's URL and stay there instead of remaining on the external website with a success message.

How can I fix this?

controller

/*
*      API Landing Page Email Form
*/
public function lpContact(Request $request)
{
    
    Mail::send('email.lpform', ['request' => $request], function ($m) use ($request) {
        $m->from('[email protected]', 'User Name');
        $m->to('[email protected]', 'John')->subject('Inquiry from Landing Page' );
    });
    // Return back to external landing page with success data
return 'Success, Your message has been sent.';

}
0 likes
5 replies
tykus's avatar

You are not redirecting; you can use the back() helper to redirect to REFERER

jpeterson579's avatar

@tykus when I submit using

return redirect()->back();

and

return back();

I get the following error

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message




/var/www/myapi/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php
    if ($request->method() == 'OPTIONS') {
        return (new Route('OPTIONS', $request->path(), function () use ($methods) {
            return new Response('', 200, ['Allow' => implode(',', $methods)]);
        }))->bind($request);
    }

    $this->methodNotAllowed($methods);
}

/**
 * Throw a method not allowed HTTP exception.
 *
 * @param  array  $others
 * @return void
 *
 * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
 */
protected function methodNotAllowed(array $others)
{
    throw new MethodNotAllowedHttpException($others);
}

/**
 * Get routes from the collection by method.
 *
 * @param  string|null  $method
 * @return array
 */
public function get($method = null)
{
    return is_null($method) ? $this->getRoutes() : Arr::get($this->routes, $method, []);
topvillas's avatar

Are you actually using AJAX to submit the form?

jpeterson579's avatar

@topvillas

Hmm actually not using ajax to submit the form. Is that the best way to accomplish this? And does that solve the issue?

topvillas's avatar

It's not an API if you're not using AJAX. Just an HTML post.

It's not the only way. Include the url to redirect back to in the post and redirect back to that.

Please or to participate in this conversation.