質問

So i have a variable in my routes.php and i want to pass it to the route::get, this is my code for more details :

$user = User::find(Auth::user()->username);
Route::get('/services/here i want to put my variable', 'ServiceController@show');

so please if someone has any idea i will be very appreciative

役に立ちましたか?

解決

The problem with variating your routes with something like:

$user = User::find(Auth::user()->username);
Route::get("/services/$user->username", 'ServiceController@show');

Is that you may enconter some problems in cases where the user does't exists. If you do that and go to your command line and execute:

php artisan routes

There will be no logged user so that route will be pointed to /services/. What you have to do to prevent those cases is to create a filter and process your route on it:

The route:

Route::get("/services/{username}", array('before' => 'user-must-be-logged-in', 'uses' => 'ServiceController@show'));

A filter to do some checks on it:

Route::filter('user-must-be-logged-in', function()
{
    if ( ! Auth::check())
    {
        App::abort(404); /// user is not logged in, this route does not exist
    }

    if ( ! User::where('username', $username)->first() )
    {
        App::abort(404); /// user does not exists, this route does not exist
    }

    if (User::where('username', $username)->first()->id !== Auth::user()->id)
    {
        App::abort(404); /// selected is not the current logged user, this route does not exist
    }
});

A controller doing whatever you need with it:

class ServiceController extends Controller {

    public function show()
    {
        $user = User::where('username', $username)->first();

        // now do whatever you need with your user;
    }

}

他のヒント

assuming its $user you want to put in there

$user = User::find(Auth::user()->username);
Route::get("/services/$user", 'ServiceController@show');

swap single quotes for doubles and pass in your var (either that or drop out of your single quotes concat in with . your var

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top