2015-10-08 175 views
1

我有一個控制器功能,需要重定向到具有不同功能的路由以避免冗餘代碼。有可能把重定向到一個不同的功能?Laravel 5控制器返回控制器

下面是代碼:

public function index() 
{ 
    $x = Auth::user()->id; 

    $id = DB::table('requests')->where('id', $x)->lists('userid'); 

    if (!is_null($id)) { 
     $frnd = DB::table('users')->whereIn('id', $id)->get(); 

     if (!is_null($frnd)) { 
      return view('friendlist', compact('frnd')); 
     } else { 
      $frnd = null; 

      return view('friendlist', compact('frnd')); 
     } 
    } else { 
     $frnd = null; 
     return view('friendlist', compact('frnd')); 
    } 
} 

public function respond() 
{ 
    $frnds = new Friend; 

    $id = Auth::user()->id; 

    $friendid = Request::input('friendid'); 

    $frnds->id = $id; 

    $frnds->friendid = $friendid; 

    if (Input::get('accept')) { 
     $frnds->save(); 
    } 

    DB::table('requests')->where('id', $id)->where('userid', $friendid)   

    return // this is where i should redirect to page with function index() 
} 

回答

0

我不認爲這是一個完美的,但有人更喜歡這種方式:重複碼

private function _index() 
{ 
    $x = Auth::user()->id; 

    $id = DB::table('requests')->where('id', $x)->lists('userid'); 

    if (!is_null($id)) { 
     $frnd = DB::table('users')->whereIn('id', $id)->get(); 

     if (!is_null($frnd)) { 
      return view('friendlist', compact('frnd')); 
     } else { 
      $frnd = null; 

      return view('friendlist', compact('frnd')); 
     } 
    } else { 
     $frnd = null; 
     return view('friendlist', compact('frnd')); 
    } 
} 

public function index() 
{ 
    $this->_index(); 
} 

public function respond() 
{ 
    $frnds = new Friend; 

    $id = Auth::user()->id; 

    $friendid = Request::input('friendid'); 

    $frnds->id = $id; 

    $frnds->friendid = $friendid; 

    if (Input::get('accept')) { 
     $frnds->save(); 
    } 

    DB::table('requests')->where('id', $id)->where('userid', $friendid)   

    $this->_index(); 
} 

私有函數。