Laravel passed argument

Viewed 27938

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?

5 Answers

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

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

In my case I had a post request to a function

$contest =  Contest::with('contestRatings')->where('id', '=', $contest_id);
return $contest;

I needed get() to make it work

$contest =  Contest::with('contestRatings')->where('id', '=', $contest_id)->get();

This issue resolved for me when I added ->get().

Try:

return $this->test->get();

Use this syntax to return your response.

return response()->json($this->test);
Related