doufu7835 2013-12-18 12:39
浏览 21

Laravel 4 Route在第一段上使用用户名

i want to undestrtand how can i setup my routes on the best way for not get collission on the future.

I would like have like first segment the username of the user showing the profile of that user.

Example: laravel.dev/user1

the problem is, if i have a route with the name register "example below" and a user put like username register of course happen a collission and is not sure on wich view is showed.

Route::get('register','UserController@getCreate');

I setup my main route for display the profile user like so:

    Route::get('{cr_user}','WallController@getIndex');    // view profile

    Route::bind('cr_user', function($value, $route) {
    if($user = User::where('username', '=',$value)->first()) // check if exist the user other ways show 404 page
    {
        return $user;
    }
    App::abort(404);
});

The second problem of this setting of route is that i cannot set other route with just 1 segment. Example if i want set the route register i cannot do that without put any segment before but for do it work i have to put example: do/register.

any help?

  • 写回答

1条回答 默认 最新

  • douchao1864 2014-01-19 20:42
    关注

    Here is how I think you can achieve the desired result. Although it's not full proof but I think it will work (I haven't tested it yet). Also like Anam said you want to put this route at the bottom of the page.

    Basically you can get the list of routes currently in Laravel App by the following:

    <?php
    $routes = Route::getRoutes();
    foreach ($routes as $r) {
        $route_names = array();
        $firstSegment = explode('/', $r->getPath());
        //echo $firstSegment[0] ."<br>";
        array_push($route_names, $firstSegment[0]);
        var_dump($route_names);
    }
     ?>
    

    You now have an array or routes first segment of the URL. Use these as a reserved word when users sign up to your App and throw an error if there is a match. This will prevent the collision. But this won't prevent you from creating a new route with a username that already exists so search your Database before adding a new route :)

    I'm pretty sure there there may be a good solution to this but this is what comes to my mind. I don't like to add /profile/ that just isn't elegant.

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程