Kames P
Kames P

Reputation: 35

How to call a model function from another model in laravel

I want to call the listcity function in another model named "property"

/model/Crawler.php

class Crawler extends Model {
public function listcity($statename)
  {

    $ins="exec Prc_Lst_CityMaster @CountryName = 'India', @StateName = '".$statename."'";

      return DB::select($ins);
  }
}

/model/Property.php

use App\Models\Crawler,
class Property extends Model {
 public function __construct(Crawler $Crawler)
    {     
        $this->Crawler = $Crawler;

    }
 public function propertyDetails($id)
    {
$this->Crawler->listcity($id);
}
}

But i get an error

ErrorException (E_NOTICE) Trying to get property of non-object

Upvotes: 1

Views: 8409

Answers (2)

user320487
user320487

Reputation:

You need to add a property for Crawler in the model.

public $Crawler;

public function __construct(Crawler $Crawler)
{     
      $this->Crawler = $Crawler;
}

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You should use relationships instead of injecting a model into another model. But if you want to do that, you need to do it manually and not through constructor:

public function propertyDetails($id)
{
    app('App\Crawler')->listcity($id);
}

Upvotes: 2

Related Questions