2016-07-27 106 views
2

我在學習Laravel方面很新。我想從數據庫獲取數據並顯示它。我能行。但我想使用標題(從數據庫中提取)作爲鏈接。但後來我得到NotFoundHttpException。 這裏是我的路線NotFoundHttpException Laravel

Route::get('articles', '[email protected]'); 

Route::get('articles/{id}', '[email protected]'); 

我控制器

class ArticleController extends Controller 
{ 
    public function index() 
    { 

     $articles=Article::all(); 

     return view('articles.index', compact('articles')); 
    } // 
    public function show($id){ 

     $article=Article::find($id); 

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

    } 

觀點

@extends('new_welcome') 
@section('content') 
     <h1> Articles </h1> 

     @foreach($articles as $article) 
      <article> 
       <h2> 


        <a href="{url ('/articles',$article->id)}">{{$article->title}}</a> 

       </h2> 
       <div class="body">{{ $article->body}}</div> 
      </article> 
    @endforeach 
@stop 

有人可以幫助我在這種情況下?

+0

其一,你有你'指數3'return'語句()'函數... –

+0

錯誤意味着它不能找到路線,什麼是你輸入網址? –

+0

對於兩個,您沒有定義的路由來顯示單個'article',這是'NotFoundHttpException'的來源。 –

回答

0

您的問題是,因爲你已經 「吃」 一個大括號(刀片引擎跳過吧):

是:

href="{url ('/articles',$article->id)}" 

必須是:

href="{{url ('/articles',$article->id)}}" 

爲你說:

如果我點擊任何單一的文章標題,然後它無法顯示我的 特定文章。但是,如果我給URL「homestead.app/articles/2」;

,所以你可以看到,當您點擊鏈接瀏覽器的地址欄將變爲:

homestead.app/{url ('/articles',$article->id)} 



因爲你是初學者所以我給你的建議,以不使用url()助手在視圖中設置直接網址。

如果您想讓應用程序在將來可以正常使用,則命名路線會更好您決定將網址從articles更改爲artcls。在這個命名的路線將保存您從視圖文件中批量更改URL。

集名稱使用'as'指令,讓您的路由靈活更改(當你需要,所以你只改變路徑,並保留觀點不變,改變URL),您的路線:

Route::get('articles/{id}', ['as' => 'article', 'uses' => '[email protected]']); 
Route::get('articles', ['as' => 'articles', 'uses' => '[email protected]']); 

更改視圖文件(找到在HREF route助手):

@extends('new_welcome') 
@section('content') 
    <h1> Articles </h1> 

    @foreach($articles as $article) 
     <article> 
      <h2> 

       <a href="{{ route('article', $article->id) }}">{{$article->title}}</a> 

      </h2> 
      <div class="body">{{ $article->body}}</div> 
     </article> 
    @endforeach 
@stop 
+0

這種方法不起作用。 – Tasmin

+0

好像您的網絡服務器不能正確重寫 – num8er

+0

我可以在點擊任何特定文章後向您顯示我獲得的網址嗎? – Tasmin