Reputation: 172
I have problems getting Cookie, I define a cookie in one middleware "CheckReferral", but when I call the cookie in one Controller the cookie return null, I check the cookie in the browser, and the cookie is good in the browser, I don't know what is the problem with the cookie... I've googled too much and this is my last resource, Someone can help me?
Here is the code of the middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckReferral
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->hasCookie('referral')) {
return $next($request);
} else {
if ($request->query('ref')) {
return redirect($request->fullUrl())->withCookie(cookie()->forever('referral', $request->query('ref')));
}
}
return $next($request);
}
This is how I call the cookie in the controller:
protected function create(array $data)
{
// $referred_by = User::where( 'affiliate_id', Cookie::get( 'referral' ) )->first();
// $referred_user = Cookie::get( 'referral' );
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => $this->uniqueRandomString(),
'referred_by' => Cookie::get('referral'),
]);
}
Here is the cookie stored in the browser:
Here is the database... the field referred_by, is stored as null, but should store the Value of the cookie:
Thank a lot, I hope resolve the problem, and know the cause...
Upvotes: 0
Views: 2462
Reputation: 172
I've solved it using vanilla PHP, the global variable $_COOKIE
protected function create(array $data)
{
// $referred_by = User::where( 'affiliate_id', Cookie::get( 'referral' ) )->first();
// $referred_user = Cookie::get( 'referral' );
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => $this->uniqueRandomString(),
'referred_by' => $_COOKIE['referral'],
]);
}
Where Cookie::get('referral')
is $_COOKIE['referral']
is not a Elegant solution, but work...
Upvotes: 0
Reputation: 457
Make sure you've defined that middleware in app\Http\Kernel.php
. Specifically in the 'web'
array there.
Imported the middleware in your web.php
( routes ) file.
..and finally added that middleware for your route like so:
Route::web('/', ['middleware' => CheckReferral']
If you've already done so then make sure you've added referred_by
column to the $fillable[]
array of your User
model.
Edit. This will do:
\Request::cookie('referral');
Upvotes: 1