Search code examples
eloquentphp-closures

Pass Eloquent Model As An Closure Argument In PHP


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.


Solution

  • 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);
    });