Laravel 传递参数

som*_*ove 5 php laravel

我的 Laravel 应用程序有一些问题。我正在尝试制作刮刀,它看起来像这样。

<?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;
    }
Run Code Online (Sandbox Code Playgroud)

如您所见,我在应用程序中创建了名为 Scraper 的新文件夹,我有 Amazon.php 文件,如下所示:

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这总是返回错误,如

类型错误:传递给 Symfony\Component\HttpFoundation\Response::setContent() 的参数 1 必须是字符串类型或 null,给定的对象,

我究竟做错了什么?

小智 13

我相信问题是返回(return $this->test),您应该使用的对象本身return response()->json([$this->test]);