我试图写一个视图作曲家,
class CountryCodeComposer
{
function compose($view)
{
$code = substr(file_get_contents('http://ipinfo.io/' . $request->getClientIp() . '/country'), 0, 2);
$view->with('code', $code);
}
}
但此代码显示错误Undefined variable: request
,
如何将$request
传递给撰写方法?
答案 0 :(得分:8)
将$request->getClientIp()
替换为request()->getClientIp()
答案 1 :(得分:3)
如果有人正在寻找全局request()
帮助函数的替代方法。这是一个例子:
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
/**
* Connect Http Request class
*/
use Illuminate\Http\Request;
class ExampleComposer
{
private $request;
/**
* Pass $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
public function compose(View $view)
{
// use $this->request
}
}