mrbrightside
mrbrightside

Reputation: 79

Laravel 5 controller returns controller

i have a controller function that needs to be redirected to a route with a different function to avoid redundancy of codes. is it possible to put a redirect to a different function?

Here is the code:

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()
}

Upvotes: 1

Views: 52

Answers (2)

fico7489
fico7489

Reputation: 8560

I don't think is a perfect, but someone prefer this way:

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();
}

private function for repeated code.

Upvotes: 0

Silwerclaw
Silwerclaw

Reputation: 695

Name the index route in routes definition like this

Route::get('home', ['uses' => 'YourController@index', 'as' => 'home']);

Then use redirect method to redirect to this route:

return redirect()->route('home');

For more info on redirects use official docs

http://laravel.com/docs/5.1/responses#redirects

Upvotes: 1

Related Questions