简体   繁体   中英

Error with laravel: Trying to get property 'id' of non-object

I'm fairly new to Laravel, but I'm trying to make a small API for my course. I've got this route Route::get('films/search', 'App\Http\Controllers\FilmController@search'); which calls my custom function search which get as a parameter a Request. Here it is:

    public function search(Request $request)
    {
        $keyword = $request->input('keyword');
        $rating = $request->input('rating');
        $minLength = $request->input('minLength');
        $maxLength = $request->input('maxLength');

        if ($this->isParamExisting($keyword)) {
            return $this->getFromKeyword($keyword);
        } elseif ($this->isParamExisting($rating)) {
            return $this->getRatings($rating);
        } elseif ($this->isParamExisting($minLength)) {
            return $this->getMinLength($minLength);
        } elseif ($this->isParamExisting($maxLength)) {
            return $this->getMaxLength($maxLength);
        } else {
            return $this->getAllFilms();
        }
    }

At first it was working, but thenm I added joins in my models for other foreign keys and now it gives me Trying to get property 'id' of non-object and says it comes from my resource which is also used by my index method which works. I don't see any reason why it wouldn't work.

It may come from my route since when I put @index instead of my custom method it still gives me the error message. And I know my index works, because I'm using it on another route and there is no problem.

Solution:

The problem was coming from one of my other routes. I add one which used films/{id} and the system thought that search was used as an {id} . I changed my route for Route::get('films/search/param', 'App\Http\Controllers\FilmController@search');

the error because you're trying access an id which doesn't exist in your database. can you show me the code In your model. and the functions that you call it In search method.

Solution:

The problem was coming from one of my other routes. I add one which used films/{id} and the system thought that search was used as an {id}. I changed my route for Route::get('films/search/param', 'App\Http\Controllers\FilmController@search');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM