2015-10-14 102 views
0

我在数据库中有几篇文章,我试图通过搜索它的标题找到一个特定的文章。这是我的控制器。laravel ::找不到类

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

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

} 

这是我在phpStorm得到错误:方法“findOrFail”不上课应用程序/条找到。

这是我的模型:

<?php 

    namespace App; 

    use Illuminate\Database\Eloquent\Model; 



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

这是我的看法,我正在试图展现文章的标题和描述。

@extends('layouts.master') 

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

    @section('content') 



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


    <article> 

     {{$article->description}} 

    </article> 

    @stop 

当我尝试加载我得到以下错误的观点:

试图让非对象(查看物业:/var/www/resources/views/article/show.blade。 php)

回答

1

find()方法不适用于任何你想要的属性。你必须通过文章的ID来实现这一点。同时通过标题而不是id找到文章要慢得多。 但如果你真的想这样做,你可以写这样的:

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

那么在你看来,这样做:

@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

检查文档进行进一步参考: http://laravel.com/docs/5.1/eloquent#retrieving-single-models

0

1.查找具体标题文章

Article::where('title', '=', $title) 

方法find()正在寻找在Model类中定义的主键(默认是id列)。

2. compact()功能

观点,因为你发送一个数组来查看,而不是对象抛出一个错误。

(PHP 4, PHP 5, PHP 7)

compact — Create array containing variables and their values

然后在你Controller变化compact('article')$article或刀片文件更改语法阵列($article['description'])。

0

尝试

$article = Article::all()->find($title); 

Laravel 5.3

+0

请给予更多的解释,为什么这是正确的答案,以便将来游客可以理解的。 – Fencer04

+0

非常不好的做法,获取所有文章,然后过滤收藏? –