1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.