I have been trying to Call a Method in Model from a Controller Class in Laravel 5...
I tried using static
keyword for the method in the Model and got it working... But i couldnt make it static in future...
Controller File
<?php
namespace App\Http\Controllers;
use App\Offer;
class TestController extends Controller {
public function testFunction()
{
$lat = "12.971891";
$lon = "77.5945627";
$radius = "10";
$result = Offer::featuredOffers($lat, $lon, $radius);
return response()->json($result);
}
}
Model File
//Model to Return Featured Offers
public static function featuredOffers($lat="", $lon ="", $radius="")
{
//Return All Featured Offers if any of the Params Missing
if(($lat == "") || ($lon == "") || ($radius == "")){
return Offer::select("_id","bannerimage","offername", "offer")->where("featured","=", 1)->where("bannerimage", "!=", "")->where('expirydate', '>', new DateTime('-1 day'))->where('startdate', '<', new DateTime())->where("status", "=", 1)->get();
}
else{
//Would Add more complex code here later
return "Lon :".$lon." | Lat :".$lat." | Radius :".$radius."";
}
}
As of now it works.. But as soon as I remove the static
keyword from the Method.. It doesnt... I read somewhere i have to instantiate an Object for calling the Model method from Controller... I'm now grasping OOP concepts and Laravel.. How should I do it the proper way.
Could somebody help out
You just instantiate an instance of your model:
public function testFunction()
{
$lat = "12.971891";
$lon = "77.5945627";
$radius = "10";
$offer = new Offer();
$result = $offer->featuredOffers($lat, $lon, $radius);
return response()->json($result);
}