When a new user visits my site I want to redirect them to /welcome but only once, I thought to do this I could use cookies and set a cookie forever once they had visited the welcome page and then checking if the cookie existed before sending them to /welcome.
Here I have a base controller
class BaseController extends Controller
{
public function __construct(Request $request)
{
$this->checkWelcome($request);
}
private function checkWelcome(Request $request) {
$currentRoute = Route::currentRouteName();
if ($currentRoute != 'frontend.guest.welcome' && Cookie::get('visited_welcome') != '1') {
header('location: ' . route('frontend.guest.welcome'));
exit();
}
}
}
When sending to frontend.guest.welcome
it has a route to WelcomeController
Route::get('/welcome', ['uses' => 'WelcomeController@getView', 'as' => 'frontend.guest.welcome']);
Here is WelcomeController
class WelcomeController extends BaseController
{
public function getView()
{
Cookie::forever('visited_welcome', '1');
return view('frontend.guest.welcome');
}
}
The issue is, its constantly sending to /welcome, not once but always.
You aren't returning the cookie with the response, attach it to the response like so:
public function checkWelcome(Request $request) {
{
if (!$request->cookie('visited_welcome')) {
return redirect('frontend.guest.welcome')->withCookie(Cookie::forever('visited_welcome', '1'));
}
// otherwise proceed as normal
}
Alternatively, you can use the queue
method on the Cookie facade:
Cookie::queue(Cookie::forever('visited_welcome', '1'));
https://laravel.com/docs/5.5/responses#attaching-cookies-to-responses
A better approach may be using middleware, that way you wouldn't need to implement any check in your controller code. For example:
// CheckIfFirstTimeVisit.php
public function handle(Request $request, Closure $next)
{
if ($request->cookies->has('visited_welcome')) {
return $request($next);
}
return response()->view('frontend.guest.welcome')
->withCookie(Cookie::forever('visited_welcome', '1'));
}
try to except your cookie in app\Http\Middleware\EncryptCookies.php
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
'visited_welcome'
];
}