Search code examples
phplaravelweb-scrapinghomesteadlaravel-5.8

Class name problem on laravel 5.8 with Request->input


I'm trying to follow a tutorial to create a simple web scraper here using Laravel, but symfony threw a "Class name must be a valid object or string" error on line 49. In phpstorm it did gave me a light warning of field accessed with magic method on $website->title

I've tried to declare $title as a public var in my App/Website.php but it still gave me this error.

here's the snippet of the code with error

    public function store(Request $request)
    {
        $this->validate($request,[
            'title'=>'required',
            'url'=>'required',
            'logo'=>'required'
        ]);

        $website = new Website();

        $website->title = new $request->input('title');

        $website->url = $request->input('url');

        $website->logo = $this->uploadFile('logo', public_path('uploads/'), $request)["filename"];

        $website->save();

        return redirect()->route('websites.index');
    }

    /**
     * Display the specified resource.
     *

and here's my App/Website Class:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Website extends Model
{
    protected $table = "website";
    public $title;
    /**
     * @var array|string|null
     */
    public $url;
    public $logo;

}

It should've saved the title, url and logo to a sql db i named scraper but it keeps throwing this error. Please help.

Edit 2: I apologize it seems i copied the code shown by symfony, my actual WebsiteController is like this copied wrong code again, here's the actual actual code:

public function store(Request $request)
    {
        $this->validate($request,[
            'title'=>'required',
            'url'=>'required',
            'logo'=>'required'
        ]);

        $website = new Website();

        $website->title = new $request->input('title');

        $website->url = $request->input('url');

        $website->logo = $this->uploadFile('logo', public_path('uploads/'), $request)["filename"];

        $website->save();

        return redirect()->route('websites.index');
    }

Solution

  • Here new should not be there ,$website->title = new $request->input('title'); , You are not making object from any class. i guess you miss type.

    and you can still get your data by just $request->title; i prefer this because it short your code and still readable.

    Do it like below

    $website->title = $request->input('title');

    Or

    $website->title = $request->title; and also for saving data into db you don't need to declare variable.

    simply in model add protected $fillable=['title','url','logo'];

    or if you using save() method you don't even need to add $fillable