Here is my simple App\Libraries\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;
}
}
}
I am using this class in my PagesController.php controller as follows,
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');
}
}
However, when I run this code I get this error,
ErrorException in GeoLocation.php line 28:
Argument 1 passed to App\Libraries\GeoLocation::getLocation() must be an instance of Illuminate\Http\Request, none given, called in /var/www/blogs/app/Http/Controllers/PagesController.php on line 22 and defined
You are not passing the request as argument in the index method, try this:
You simply need to inject
Request
in Geolocation constructor like so: