Side
Side

Reputation: 1751

Laravel best or effective way to handle if else statement

i am stuck a bit, i have lot of if else statement handeling, and i will need to use this in more the none page, so handeling it in the view is not a good idea (and read about it its not a good idea)

So what im am stuck with i have 2 tables.

user
users_details

User table stores basic login information and and the user details has the following fields

user_id
first_name  
last_name   
company 
location    
experience  
compensation    
about   
gender  
year    
day 
month   
profile_image

my relations

User model

public function detail()
{
   return $this->has_one('Detail');
}

Details model

public function user()
{
   return $this->belongs_to('User');
}

So what im stuck with is how to handle the object to return experience, compensation because those what i will need on more than one page, at first i did this in my controller

public function get_index($username = null)
{

   $user = User::get_profile($username);

   if (is_null($user))  return Response::error('404');

   switch ($user->detail->experience) {
    case 1:
        $user->detail->experience = "No experience";
    break;

    case 2:
        $user->detail->experience = "Some experience";
    break;

    case 3:
        $user->detail->experience = "Experienced";
    break;

    case 4:
        $user->detail->experience = "Very experienced";
    break;

   }

    switch ($user->detail->compensation) {
    case 1:
        $user->detail->compensation = "Any";
    break;

    case 2:
        $user->detail->compensation = "Depends on Assignment ";
    break;

    case 3:
        $user->detail->compensation = "Paid Assignments Only ";
    break;

    case 4:
        $user->detail->compensation = "Time for Print ";
    break;

   }

   $this->layout->title = 'Profile' . ' ' . $username ;

   $this->layout->content = View::make( 'user.profile' )->with( 'user', $user );

}    

And i know this is the worts idea i should come up with because it wont solve my problem, not effective and i still need to duplicate.

So could someone show me and example and effective way to handle these?

Would be grateful, thank you

Upvotes: 0

Views: 1168

Answers (1)

Tigra
Tigra

Reputation: 2631

Well, this is weird, indeed.

But, you have 2 ways:

1) Define tables for answers and join with your user table, so SQL result will return string, not ID

2) If you still want for a some reason to associate ID to Text on code level you can do following:

Define method in details model, like compensation_str() which will make this switch, same for expierence. And in each place you need to display this text you call this method ($user->details->compensation_str())

Upvotes: 2

Related Questions