Reputation: 900
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)
Upvotes: 0
Views: 13934
Reputation: 2474
Article::where('title', '=', $title)
Method find()
is looking for primary key defined in Model
class (by default is id
column).
compact()
functionView throws an error because you send an array to view, not the object.
(PHP 4, PHP 5, PHP 7)
compact — Create array containing variables and their values
Then in your Controller
change compact('article')
to $article
or change syntax in your blade file to array ($article['description']
).
Upvotes: 0
Reputation: 5387
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
Upvotes: 3