Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter if URL segment is missing

Having found out that 3rd URL segments can be passed directly to the a function's parameter I did the following.

URL example:

http://www.mysite.com/profile/user/64

Function in profile controller:

function user($user_id) //$user_id is 3rd URL segment
{
   //get data for user with id = $user_id
}

Using $this->uri->segment(3) returns FALSE is no segment exists. With the function parameter I get

Missing argument 1

How can I return FALSE and not execute the function if the 3rd URL segment is missing? I'm looking for a simple solution without if statements, if possible.

like image 971
CyberJunkie Avatar asked Aug 07 '26 14:08

CyberJunkie


2 Answers

You get "Missing argument 1" because the function does not get the argument.

Try

function user(){
    if($this->uri->segment(3)){
        //get data for user with id = $this->uri->segment(3)
    }
}
like image 175
Alfonso Rubalcava Avatar answered Aug 10 '26 05:08

Alfonso Rubalcava


What about default arguments:

function user($user_id = FALSE) //$user_id is 3rd URL segment
{
   //get data for user with id = $user_id
}
like image 31
cwallenpoole Avatar answered Aug 10 '26 05:08

cwallenpoole