Sander Van Keer Sander Van Keer - 2 months ago 14
PHP Question

laravel ::find not found in class

I have a few articles in the database and I am trying to find a specific one by searching for its title. This is my controller.

public function showArticle($title)
{
$article = Article::find($title);

return view('article.show', compact('article'));

}


This is the error I get in phpStorm: Method "findOrFail" not found in class App/Article.

This is my model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Article extends Model
{
protected $fillable =
[
'title',
'description',
'published_at'
];
}


This is my view where I am trying to show the title and description of the article.

@extends('layouts.master')

@section('title', 'All articles')

@section('content')



<h1>{{$article->title}}</h1>


<article>

{{$article->description}}

</article>

@stop


When I try to load the view I get the following error:

Trying to get property of non-object (View: /var/www/resources/views/article/show.blade.php)

Answer

find() method does not work with any attribute you want. You have to pass the id of the article to achieve that. Also finding articles by title instead of id is much much slower. But if you really want to do it, you can write something like:

$article = Article::where('title', $title)->first();

Then in your view, do something like:

    @extends('layouts.master')

@section('title', 'All articles')

@section('content')

@if($article)

<h1>{{$article->title}}</h1>


<article>

    {{$article->description}}

</article>

@else
    Article not found
@endif

@stop

Check the docs for further reference: http://laravel.com/docs/5.1/eloquent#retrieving-single-models

Comments