iedmrc
iedmrc

Reputation: 752

Laravel5: Conditional Routing (to make /usernickname pages)

In laravel 5 I want to route www.example.com/username response to a user profile page if user exists, just like twitter,facebook.. Sure I have pages like /blabla, but I don't allow users to have 'blabla' for username.

In this case I tried lots of things but the last one is:middlewares. Middlewares were the best for me but In this case, User Auth is lost. If I use something like Auth::id() in controller, I get error. When I print dd(Auth::user()) I just get null.

By the way, there is no Auth problem if I switch to www.example.com/ or www.example.com/blabla etc.. Only middleware makes Auth problem.

My middleware:

  class UserMiddleware
{

    public function handle($request, Closure $next)
    {

            if (User::where('username', $request->path())->exists()) {
                $controller = App::make('App\Http\Controllers\UserController');
                return Response::make($controller->callAction('index',array()));
                //return $controller->callAction('index',array());
            }


        return $next($request);
    }
}

Kernel.php:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\UserMiddleware::class,
];

Controller:

public function index()
{
    //$user=Auth::user()->id;
    return view('front.user.profile',['user'=>Auth::user()]);
}

In view:

{{dd($user)}}

How can I overcome the losing Auth problem or do you show me how to solve it in another way?

Upvotes: 0

Views: 225

Answers (1)

Javier Gonzalez
Javier Gonzalez

Reputation: 311

I have another approach for you. I create a profiles table in the database with the fields id, user_id and username. Then I add the following relations in the models.
User Model

    public function profile()
    {
        return $this->hasOne('App\Profile');
    }

Profile Model

    public function user()
    {
        return $this->belongsTo('App\User');
    }

In the ProfilesController I add the following:

    public function __construct()
    {
        $this->middleware('auth');
    } 


    public function show($username)
    {

        $profile = Profile::where('username', $username)->first();

        return view('front.user.profile', compact('profile'));
    }

Dont forget use App\Profile; in the Controller.
In your View you can make something like this:

Auth::user()->profile->username

Upvotes: 1

Related Questions