这是我的简单应用\库\Gelocation.php class,
namespace App\Libraries;
use Location;
use Illuminate\Http\Request;
class GeoLocation
{
public function getLocationByIP($ip = null)
{
// If IP address is set
if ($ip) {
$location = Location::get($ip);
} else {
$location = Location::get();
}
// Get the location by city
return $location->cityName;
}
public function getLocationByCoordinates($longitute, $latitude)
{
//
}
public function getLocation(Request $request)
{
// Check if the location is already set in the cookie
if ($request->cookie('location')) {
return $request->cookie('location');
} else {
$location = $this->getLocationByIP();
// Set location in the cookie
$request->cookie()->forever('location', $location);
return $location;
}
}
}
我在我的课程中使用这个课程页面控制器.php控制器如下,
namespace App\Http\Controllers;
use App\Libraries\GeoLocation;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PagesController extends Controller
{
public $location;
public function __construct(GeoLocation $location)
{
$this->location = $location;
}
public function index()
{
dd($this->location->getLocation());
return view('pages.index');
}
}
但是,当我运行此代码时,我收到此错误,
GeoLocation.php 第 28 行中的 ErrorException:
传递给 App\Libraries\GeoLocation::getLocation() 的参数 1 必须是
Illuminate\Http\Request 的实例,未给出,在中调用
/var/www/blogs/app/Http/Controllers/PagesController.php 第 22 行和
定义的
你只需要注入Request
在 Geolocation 构造函数中,如下所示:
namespace App\Libraries;
use Location;
use Illuminate\Http\Request;
class GeoLocation
{
public function __construct(Request $request){
$this->request = $request;
}
public function getLocationByIP($ip = null)
{
// If IP address is set
if ($ip) {
$location = Location::get($ip);
} else {
$location = Location::get();
}
// Get the location by city
return $location->cityName;
}
public function getLocationByCoordinates($longitute, $latitude)
{
//
}
public function getLocation() //no need to inject here
{
// Check if the location is already set in the cookie
if ($this->request->cookie('location')) {
return $request->cookie('location');
} else {
$location = $this->getLocationByIP();
// Set location in the cookie
$request->cookie()->forever('location', $location);
return $location;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)