Pass Eloquent Model As An Closure Argument In PHP

42 Views Asked by At

I'm using Laravel Illuminate/Database outside of laravel application. I'm trying to pass the Eloquent model as my closure argument but its throwing an error. May be I'm passing it wrongly. My code is as following:

      // Create a dummy subject (This is working absolutely fine)
        SubjectModel::create(array(
            'title' => 'Mathematics',
            'description' => 'Math Subject',
            'slug' => 'math',
            'ka_url' => 'http://khanacademy.org/math'
        ));


        $scrapper = new SubjectScrapper();
        $scrapper->setUrl('');

This is not working. SubjectModel is not being passed in the following closure

          $scrapper->runScrapper(function($subjects) use ($scrapper, SubjectModel $subjectModel) {

            if(!empty($subjects))
            {
                foreach ($subjects as $subject) {
                    $urlParts = explode('/', $subject['url']);
                    $slug = end($urlParts);
                    $subjectModel::create(array(
                        'title'     => $subject['subject_name'],
                        'slug'      => $slug,
                        'ka_url'    => $scrapper->getBaseUrl().$subject['link'],
                    ));
                }
            }
        });

Could anybody please tell me how to accomplish this task.

1

There are 1 best solutions below

0
Viral Solani On BEST ANSWER

Try this. No need to pass object in closure

$scrapper = new SubjectScrapper();
$scrapper->setUrl('');
$scrapper->runScrapper(function($subjects) use ($scrapper, $output) {

  SubjectModel::create(array(
      'title'     => 'Math',
      'slug'      => 'math',
      'ka_url'    => 'http://math'
  ));

    $output->writeln('<info>Total Subjects Scrapped:: '.count($subjects).'</info>'.PHP_EOL);
});