0

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

1
  • How and why do you need to variate your routes? Commented Mar 26, 2014 at 17:43

2 Answers 2

1

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

}
Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

You cannot pass a whole object like this in a string.
looks to me like he's returning a authed users username not the entire object but I don't use laravel so its just a stab in the dark :)
This find() method will return a really big object. :)
Would have to User::find(...)->username it again to get the username.
ahh in which case perhaps i should put a disclaimer "in any sensible framework" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.