Laravel设置cookie不起作用 [英] Laravel set cookie not working
问题描述
我在自定义中间件中有以下代码:
I have the following code in a custom middleware:
public function handle($request, Closure $next)
{
if($request->hasCookie('uuid')) {
return $next($request);
}
$uuid = 99;
$response = $next($request);
return $response->withCookie(cookie()->forever('uuid', $uuid));
}
我已经在app.php文件中注册了中间件,但cookie仍未写入。任何人都可以帮忙。另外,上述内容可以作为单例运行,以便在应用启动时执行一次吗?
I have registered the middleware in the app.php file, but cookies is still not being written. Please can anyone help. Additionally can this above be run as a singleton, so that it is executed once on app start?
谢谢
推荐答案
在这里,我会在下面的laravel简单示例中提到set并获取一个cookie。
Here, I'm mention set and get a cookie in laravel simple example following.
首先创建一个控制器。
First of the create a controller.
1. php artisan make:controller CookieController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CookieController extends Controller {
**/* below code a set a cookie in browser */**
public function setCookie(Request $request){
$response = new Response('Hello World');
$response->withCookie(cookie('name', 'Anything else'));
return $response;
}
**/* below code a get a cookie in browser */**
public function getCookie(Request $request){
$value = $request->cookie('name');
echo $value;
}
}
在路线/ web.php文件(Laravel 5.4)
Add a following line code in routes/web.php file (Laravel 5.4)
Route::get('/cookie/set','CookieController@setCookie');
Route::get('/cookie/get','CookieController@getCookie');
与运行程序相比,所有文件加载项项目都易于设置并获取Cookie。
And all files add-in project than a run program easily sets and get a cookie.
这篇关于Laravel设置cookie不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!