【发布时间】:2018-08-12 18:18:26
【问题描述】:
我一直在尝试了解如何像多语言环境一样使用多国网站,以便根据用户的位置将用户重定向到他所在国家/地区的特定列表。
我正在学习 laravel,从我的学习中,我尝试了类似下面的方法,显示错误并且需要有人纠正我以继续我的学习。
App\Models\Country.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
protected $table = 'countries';
}
routes\web.php
Route::group(['prefix' => '{country}', 'middleware' => 'country'], function(){
Route::get('/', 'Frontend\PagesController@index')->name('welcome');
});
App\Http\Middleware\CountryMiddleware.php
<?php
namespace App\Http\Middleware;
use App\Models\Country;
use Closure;
use Request;
use Route;
class CountryMiddleware
{
public function handle($request, Closure $next)
{
$countryShortcode = $request->route('country');
$routeName = $request->route()->getName();
$routeParameters = $request->route()->parameters();
if ($request->session()->has('redirect_to_country')) {
$redirectTo = $request->session()->get('redirect_to_country');
if ($country === $redirectTo) {
$request->session()->forget('redirect_to_country');
} else {
$routeParameters['country'] = $redirectTo;
return redirect()->route($routeName, $routeParameters);
}
}
$country = Country::where('country_shortcode', '=', $countryShortcode)
->where('is_active', '=', 1)->first();
if ($country === null) {
return redirect('/');
}
$request->session()->put('country', $country);
$request->session()->save();
return $next($request);
}
}
迁移:2018_08_12_225010_create_countries_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('country_name');
$table->string('country_shortcode')->unique();
$table->tinyinteger('is_active');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('countries');
}
}
我在数据库中创建了三个国家,即United States,短代码USA,United Kingdom,短代码UK,Australia,短代码AUS。
当我转到 www.example.com 时,它会说:
页面未找到。 当我去
www.example.com/USA它说:反射异常 (-1) 类国家不存在
1 - 如何解决这个问题?
2 - 如何自动检测用户位置代码并重定向到他们的位置路线?喜欢美国的用户到www.example.com/USA。
3 - 在我的控制器中,我想从路由中获取国家代码并执行以下操作:
$code = $request->route('country');
Professionals::where('short_code', $code)->latest()->paginate(10);
4 - 对于www.example.com,它显示为not found 404 页面。如何显示具有所有位置的普通网站。我需要指定组外的路线吗?
以便根据用户位置列出该国家/地区的正确专业人员。
【问题讨论】:
-
你想请告诉我你在中间件的
if ($country === $redirectTo)中找到$country吗?
标签: laravel laravel-5.6