简体   繁体   中英

How to use laravel 4 routes correctly?

I'm really new in Laravel.

Context:

  • I created 2 migrations (users_table and posts_table).
  • I created 2 models with correct relationship between User and Post.
  • I seed some data in my database.

But I'm a little bit confusing about routes and view.

This is my prototype:

// Posts

Route::get('add', 'PostsController@add');
Route::post('add', 'PostsController@store');

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


// Users

Route::get('login', 'UsersController@login');

Route::get('logout', 'UsersController@logout');

Route::get('profile', array(
    'before' => 'auth',
    'uses' => 'UserController@profile'
));

Route::get('register', UsersController@register');

Route::post('register', 'UsersController@store');

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

What would you do for this simple example?

I don't really know how to implement slug routing in an appropriated way.

Do you have good examples with appropriated routing and seo? (Github / BitBucket)

Thanks!

This is an example route for post slug:

Route::get('posts/{slug}', array('as' => 'posts.show', 'uses' => 'PostsController@show'));

And the controller show method:

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');
    }
}

In your model you can add a find by slug method:

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

And to save your slug, something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM