Php 基于会话在视图中显示数据
我有一个带有语言列“lang”的帖子表,我只想在视图中显示会话中存储的带有语言的帖子 但我一直得到的只是带有默认语言(Fr)的帖子 控制器:Php 基于会话在视图中显示数据,php,laravel,session,controller,multilingual,Php,Laravel,Session,Controller,Multilingual,我有一个带有语言列“lang”的帖子表,我只想在视图中显示会话中存储的带有语言的帖子 但我一直得到的只是带有默认语言(Fr)的帖子 控制器: public function index(Request $request) { if ($request->session()->has('en')) { $posts = Post::where('lang','=','En') ->with('author','ta
public function index(Request $request)
{
if ($request->session()->has('en')) {
$posts = Post::where('lang','=','En')
->with('author','tags','category','comments')
->latestFirst()
->filter(request()->only(['term', 'year', 'month']))
}
elseif ($request->session()->has('ar')) {
$posts = Post::where('lang','=','Ar')
->with('author','tags','category','comments')
->latestFirst()
->filter(request()->only(['term', 'year', 'month']))
}
else {
$posts = Post::where('lang','=','Fr')
->with('author','tags','category','comments')
->latestFirst()
->filter(request()->only(['term', 'year', 'month']))
}
return view("blog.index", compact('posts'));
}
从应用程序实例获取当前区域设置,并回退到
Fr
,因为它是默认设置
公共功能索引(请求$Request)
{
$locale=ucfirst(app()->getLocale());
$posts=Post::where('lang',$locale)
->带有('author'、'tags'、'category'、'comments')
->latestFirst()
->筛选(请求()->only(['term','year','month']);
返回视图(“blog.index”,compact(“posts”);
}
希望这对您有所帮助,因为键“Ar”或“En”没有会话值 你有两个选择。通过中间件或trait,可以在需要时在控制器类中使用 请注意,如果您使用我将要发布的这个选项,搜索机器人将遇到一个问题,因为URL完全相同。对我的项目来说,这并不重要,但对你的项目来说,这可能是重要的。如果你不想这样做,你必须选择将它添加到你的路线中() 如果您选择使用中间件,要更改语言,您必须在任何路由?lang=en或?lang=fr中添加一次,然后会话将记住选择 中间件
namespace App\Http\Middleware;
use Closure;
class Language
{
/**
* The availables languages.
*
* @array $languages
*/
protected $languages = ['en', 'ar', 'fr'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->session()->has('lang'))
{
$request->session()->put('lang', $request->getPreferredLanguage($this->languages));
}
if ($request->has('lang'))
{
$request->session()->put('lang', $request->get('lang'));
}
app()->setLocale($request->session()->get('lang'));
return $next($request);
}
}
如果新来访者到达,他或她将以首选语言(在您的情况下为法语)接受服务。现在,对另一种语言的任何选择都会作为session('lang')
保存在代码中的任何位置
$posts = Post::where('lang','=', session('lang', 'fr')->...