Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel passed argument

Tags:

php

laravel

I have some problems with my Laravel app. I'm trying to make scraper and It looks like this.

<?php

namespace App\Http\Controllers;

use App\Scraper\Amazon;
use Illuminate\Http\Request;

class ScraperController extends Controller
{
    public $test;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->test = new Amazon();
       
        return $this->test;
    }

As you can see I have created new folder inside app that is called Scraper, and I have Amazon.php file that looks like:

<?php

namespace App\Scraper;

use Goutte\Client;

class Amazon
{
    public string $test = ''; 

    public function __construct()
    {
        return "test";
    }

    public function index()
    {
        $client = new Client();
        
        $crawler = $client->request('GET', 'https://www.amazon.co.uk/dp/B002SZEOLG/');

        $crawler->filter('#productTitle')->each(function ($node) {
            $this->test = $node->text()."\n";
        });

        return $this->test;
    }
}

And this is always returning error like

TypeError: Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given,

What am I doing wrong?

like image 681
somebodytolove Avatar asked Aug 08 '20 20:08

somebodytolove


2 Answers

I believe the problem is returning the object itself (return $this->test), you should use return response()->json([$this->test]);

like image 116
sromeu Avatar answered Sep 28 '22 19:09

sromeu


return var_dump($node->text()); before return $this->test to be sure test() is returning the expected value.

like image 37
Igiri David Avatar answered Sep 28 '22 19:09

Igiri David