Setting Cookie in Laravel Custom Middleware
<p>I want to set a cookie in a custom Laravel middleware. The idea is to set the cookie value any time a user visits my website through any landing page.</p>

<p>So what I did was I created a middleware named <code>UUIDMiddleware</code>. I am using this middleware along with web middleware in my routes. Below is its code from the middleware.</p>

<pre class="lang-php prettyprint-override"><code>if($request-&gt;hasCookie('uuid'))
{
    return $next($request);    
}
else
{
    $uuid = Uuid::generate();
    $response = new Response();
    return $response-&gt;withCookie(cookie()-&gt;forever('uuid', $uuid));
}
</code></pre>

<p>As you can see I am checking if cookie exists. If not, I am passing control to next request.</p>

<p>The problem is when setting a cookie using <code>return $response</code>, I cannot pass control to next request. How do I resolve this?</p>

<p>What happens in this case is if a cookie is not set, it sets a cookie and a blank screen shows up. If I refresh, I see the website with a cookie set.</p>

<p>There has to be a way to set cookie using middleware in the right way. How do I do it?</p>