2015-05-23 40 views
0

當我去「/ todos和/ todos/id」時,我遇到了我在laravel的路由問題,但是當我嘗試使用「/ todos/create」時,我得到了一個N​​o查詢結果[TodoList ] 我是新來這個,請幫我...我真的不想放棄,因爲我真的很喜歡這個MVC在Laravel爲什麼我會得到模型[TodoList]的否查詢結果?

這裏是我的路線

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

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

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


Route::get('db', function() { 

    $result = DB::table('todo_lists')->where('name', 'Your List')->first(); 
    return $result->name; 

}); 

Route::resource('todos', 'TodoListController'); 

模型

<?php 

class TodoList extends Eloquent {} 

控制器

public function index() 
    { 
     $todo_lists = TodoList::all(); 
     return View::make('todos.index')->with('todo_lists', $todo_lists); 
    } 


    /** 
    * Show the form for creating a new resource. 
    * 
    * @return Response 
    */ 
    public function create() 
    { 
     $list = new TodoList(); 
     $list->name = "another list"; 
     $list->save(); 
     return "I am here by accident"; 
    } 


    /** 
    * Store a newly created resource in storage. 
    * 
    * @return Response 
    */ 
    public function store() 
    { 

    } 


    /** 
    * Display the specified resource. 
    * 
    * @param int $id 
    * @return Response 
    */ 
    public function show($id) 
    { 
     $list = TodoList::findOrFail($id); 
     return View::make('todos.show')->withList($list); 
    } 

我的看法

@extends('layouts.main') @section('content') 

<h1>All todo list</h1> 

<ul> 
    @foreach ($todo_lists as $list) 
    <li>{{{ $list->name }}}</li> 
    @endforeach 
</ul> 

@stop 
+0

「新TodoList」用於創建新記錄。它是有道理的,你不能得到任何查詢模型。 – edisonthk

回答

0

問題出在您爲/todos/{id}定義的顯式路由。由於此路線在resource路線之前定義,因此正在捕獲路線todos/create,並將文字create視爲show方法的{id}參數。

刪除顯式get路線爲todos/todos/create並且您的問題將被修復。這兩條路線均由resource路線處理。

+0

謝謝你!它工作,但我如何編輯資源?如果我想添加一個函數的資源,它會像這樣工作 'Route :: get('db',function(){ $ result = DB :: table('todo_lists') - > where ('name','Your List') - > first(); return $ result-> name; });' – Jayswager

+0

@JoeSantos您可以添加自定義路由,您只需確保它不與資源提供的路線衝突。所以,你可以創建一個'get'路由到'/ todos/getName',它可以正常工作。您只需要小心路由參數,以確保您不會無意中捕獲資源路由。 – patricus

0

您的模型沒有fillable屬性。嘗試添加

protected $fillable = [ 
    'name' 
]; 

您還需要定義一個表

protected $table = 'todolist'; 

額外 你還手動添加已經由您的資源控制器喜歡你show路線定義了一些路線。

您還將模型存儲在您的create方法中。您應該在創建方法中顯示錶單並將結果存儲在store方法中。

+0

它沒有工作,我把它添加到模型....得到這個錯誤的語法錯誤,意外'保護'(T_PROTECTED) – Jayswager

+0

你需要添加變量可填充和表內的類,而不是它後 –

相關問題