简体   繁体   中英

Laravel 5.2 route regex

I'm trying to use the following route to capture urls like www.example.com/@username but it gives me a 404 error.

Route::get('{user}', 'UserController@showProfile')->where('user', '(?<=\s|^)@([\w@]+)');

The regex works just fine, because if i'm using the following route it outputs the correct result.

Route::get('{user}', 'UserController@showProfile')

and

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class UserController extends Controller
{
    public function showProfile($user)
    {
        $out = array();
        $re = "/(?<=\\s|^)@([\\w@]+)/";

        preg_match_all($re, $user, $out);

        dd($out);
    }
}

What am i doing wrong?

Remove your lookbehind and the capture group from your route regex. Try to use the most simple solution possible, like this ^@[\\w]+$ . And since your route will always start with @ instead of capturing the username you can do $user = substr($user, 1); .

Also I would recommend to use route model binding, so you can have an instance of an existing user directly in your controller. In your RouteServiceProvider@boot add this:

    $router->bind( 'user', function ( $username ) {
        return User::whereUsername( substr($username, 1) )->firstOrFail();
    });

And then inside your controller your method will look like this:

public function showProfile( User $user ){ ...

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