2014-01-08 167 views
0

我在Laravel真的很新。如何正確使用laravel 4路由?

上下文:

  • 我創建2點遷移(users_table和posts_table)。
  • 我創建了2個模型,用戶和帖子之間有正確的關係。
  • 我在我的數據庫中播種了一些數據。

但我對路線和視圖有點困惑。

這是我的原型:

// Posts 

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

Route::resource('posts', 'PostsController', array(
    'except' => array('create', 'store') 
)); 


// Users 

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

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

Route::get('profile', array(
    'before' => 'auth', 
    'uses' => '[email protected]' 
)); 

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

Route::post('register', '[email protected]'); 

Route::resource('users', 'UsersController', array(
    'except' => array('create', 'store') 
)); 

你會爲這個簡單的例子做什麼?

我真的不知道如何以一種適當的方式實現slug路由。

你有適當的路由和搜索引擎優化的好例子嗎? (Github/BitBucket)

謝謝!

回答

0

這是後塞一個例子路線:

Route::get('posts/{slug}', array('as' => 'posts.show', 'uses' => '[email protected]')); 

而控制器顯示方法:

class PostsController extends BaseController { 

    public function show($slug, $language = null) 
    { 
     if ($post = Post::findBySlug($slug)) 
     { 
      return View::make('posts.article')->with('post', $post); 
     } 

     return Redirect::route('posts.index'); 
    } 
} 

在你的模型,你可以通過蛞蝓方法添加一個發現:

public static function findBySlug($slug) 
{ 
    return Post::where('slug', $slug)->first(); 
} 

並保存你的slu,,如:

$post->title = Input::get('title'); 
$post->post = Input::get('text'); 
$post->slug = Str::slug(Input::get('title')); 
$post->save(); 
+0

感謝您的回答,文檔說使用動態範圍而不是findBySlug方法。我認爲使用資源會簡化我的應用程序,但我會創建自己的自定義路線。關於路線的另一個問題。您是否使用過Route :: get,Route :: post,...或Route :: any並在控制器中檢查請求? – user3064931

+0

我使用Route :: get()和Route :: post()。你在控制器上的代碼越少越好。另外,看看這篇關於路由的文章:http://philsturgeon.co.uk/blog/2013/07/beware-the-route-to-evil。 –