Jack Barham
Jack Barham

Reputation: 3209

Laravel 4 - Display a different view depending on a value in user database

I'm trying to display a profile View depending if a user has activated their account - i.e. active = 1 (or 0 for inactive)

If the user has activated their account show a View with users details of if they haven't display a different View saying they need to activate their account.

This is the code I am having trouble with:

public function user($username) {

    // Get the /username from URL and check the database
    $user = User::where('username', '=', $username);

    // If /username does exist
    if($user->count()->('active', '=', 1)) {

        // Grab user info from database
        $user = $user->first();

        // return the active user view
        return View::make('profile.active-user')->with('user', $user);

    } else {

        // Grab user info from database
        $user = $user->first();

        // return the inactive view
        return View::make('profile.inactive-user')->with('user', $user);

    }

    return App::abort(404); // else throw a 404

}

Any help/logic would be really appreciated.

Thanks, Jack.

Upvotes: 0

Views: 165

Answers (1)

Björn
Björn

Reputation: 5876

You can simplify it a bit by combining the eloquent query and 404. Also you already have your user object after the query so no need for extra eloquent stuff:

public function user($username) {

    //get user from db, if no result throw not found (404)
    $user = User::where('username', '=', $username)->firstOrFail();

    if($user->active) {
        // return the active user view
        return View::make('profile.active-user')->with('user', $user);
    } else {
        // return the inactive view
        return View::make('profile.inactive-user')->with('user', $user);
    }

}

Upvotes: 2

Related Questions