Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test logged in user has correct id in Laravel 4

I'm trying to work out how to test that the logged in user in Laravel 4 can visit the correct user account.

At the moment this is what is in my routes.php file.

Route::get('user/{id}', array('before' => 'auth', function(){
    // logged in user
    // but can visit any account!!
}));

How would I restrict this to so user/1 could only see the profile if that is the current logged in users id?

Auth::user()->id

Returns the logged in id to test against but I can't work out how to write a filter that checks it's equal to the {id} in the url.

Please help! Thanks.

like image 260
markstewie Avatar asked Apr 01 '13 04:04

markstewie


People also ask

What is auth ()- user () in laravel?

Auth::user() — You can check if a user is authenticated or not via this method from the Auth Facade. It returns true if a user is logged-in and false if a user is not. Check here for more about how Facades work in Laravel.

How can I tell if someone is logged in laravel?

use Illuminate\Support\Facades\Auth; if (Auth::check()) { // The user is logged in... }

What is Auth attempt laravel?

Auth::attempt assumes that the password being retrieved from the database is hashed.


1 Answers

Got some help through the Laravel irc channel.

This is the way I have gone with.

Route::filter('user', function($route, $request)
{
    if( $request->segment(2) != Auth::user()->id)
    {
        return Redirect::to('/login');
    }
});

Then on my route do.

Route::get('user/{id}', array('before' => 'auth|user', 'uses' => 'UsersController@index'));
like image 71
markstewie Avatar answered Nov 21 '22 14:11

markstewie