提取单个方法Laravel 5.2

I have a ProfileController right now that is checking if the current user is = to the user on the page, if not it redirects them. As you can see I have that call attached into every single method.

 if( Auth::check() && Auth::user()->username != $username) {
            // not authenticated user, so access is denied
            return redirect('/');
        }

Is there a way I can extract it to one method, (like my User.php Model Class) and then just call it with that method, instead of repeating the same process.

If so, how?

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;


class ProfileController extends Controller {


    /**
     * Get the current users profile.
     */
    public function getProfile($username) {

        // If the current username is NOT equal to the currently logged
        // in users username, then redirect them back.
        if( Auth::check() && Auth::user()->username != $username) {
            // not authenticated user, so access is denied
            return redirect('/');
        }

        // Check if user exists
        // Set 'username' = $username, with first result
        $user = User::where('username', $username)->first();

        // Return view with user.
        return view('profile.index')->with('user', $user);

    }



    /**
     * Edit your Profile
     */
    public function editProfile($username) {
        // If the current username is NOT equal to the currently logged
        // in users username, then redirect them back.
        if( Auth::check() && Auth::user()->username != $username) {
            // not authenticated user, so access is denied
            return redirect('/');
        }

        // Check if user exists
        // Set 'username' = $username, with first result
        $user = User::where('username', $username)->first();

        // Return view with user.
        return view('profile.edit-profile')->with('user', $user);
    }


    /**
     * Show your Travel Flyers in Your Profile Page
     */
    public function showYourFlyers($username) {
        // If the current username is NOT equal to the currently logged
        // in users username, then redirect them back.
        if( Auth::check() && Auth::user()->username != $username) {
            // not authenticated user, so access is denied
            return redirect('/');
        }

        // Check if user exists
        // Set 'username' = $username, with first result
        $user = User::where('username', $username)->first();

        // Return view with user.
        return view('profile.your-flyers')->with('user', $user);
    }


}

EDIT****** You mean some thing like this:

// Get Profile Dashboard
    Route::get('/user/{username}', [
        'uses' => '\App\Http\Controllers\ProfileController@getProfile',
        'as'   => 'profile.index',
        'middleware' => ['auth'],
    ]);

EDIT*********** My Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('auth.login');
            }
        }

        return $next($request);
    }

}

EDIT************ I implemented it, but now I get an error:

ReflectionException in C:\xampp\htdocs\travels\src\vendor\laravel\framework\src\Illuminate\Container\Container.php line 738:
Class CustomAuth does not exist

This is my route:

Route::group(['middleware' => ['web']], function () {

    // Other routes here also

    Route::group(["middleware" => 'CustomAuth'], function(){

        Route::get('/user/{username}', [
            'uses' => '\App\Http\Controllers\ProfileController@getProfile',
            'as'   => 'profile.index',
        ]);

    });

});

After consideration, I think it would be a good idea to develop a custom middleware file to handle this. So, create a file called CustomAuth.php in app/Http/Middleware/CustomAuth.php:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CustomAuth
{
    public function handle($request, Closure $next)
    {
        // Handle Logic of Authenticated User Here.
        $username = $request->route()->parameters()["username"];
        if(Auth::check() && Auth::user()->username != $username) {
            return redirect('/');
        }

        return $next($request);
    }
}

Next, to use the CustomAuth.php middleware that you developed, you either need to specify it specifically on a Route:: declaration or as a Route::group() function. I prefer the Route::group() as it allows you to control multiple routes, and saves typing.

Route::group(["middleware" => "custom"], function(){
   Route::get('/user/{username}', 'ProfileController@getProfile');
});

If you have this group defined, every time you try to access http://localhost/PROJECT/user/David the middleware will be fired, and it will check the the authenticated user's username against the username supplied in the route, and redirect accordingly.

Hopefully this works for you, but let me know if any errors arise. Also, I think a custom middleware is a good idea for this, as you might want to use the basic Authenticate.php on other routes.

Missed the registration. Add the following to app/Http/Kernel.php:

protected $routeMiddleware = [ 
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'custom' => 'App\Http\Middleware\CustomAuth'
];

And change ["middleware" => "CustomAuth"] to ["middleware" => "custom"]. That should fix the error.

Thanks to Tim Lewis, this is the correct answer:

Add a custom Auth Middleware like this:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CustomAuth
{
    public function handle($request, Closure $next)
    {
        // Handle Logic of Authenticated User Here.
        $username = $request->route()->parameters()["username"];
        if(Auth::check() && Auth::user()->username != $username) {
            return redirect('/');
        }

        return $next($request);
    }
}

Then call it in the Kernal:

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'custom' => \App\Http\Middleware\CustomAuth::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];

Then make the route like this:

Route::group(['middleware' => ['web']], function () {

    // Other routes here also

    Route::group(["middleware" => 'custom'], function(){

        Route::get('/user/{username}', [
            'uses' => '\App\Http\Controllers\ProfileController@getProfile',
            'as'   => 'profile.index',
        ]);

    });

});