0

I'm unable to redirect my controller to the same view index.blade.php after store method, it gives an error Undefined Variable :users, while I redirect through index method, it works fine. How do i fix this

This is UserController

public function index()
{
    $users = \App\User::all();
    return view('pages.index')->with('users',$users);
}

public function create()
{
    $users = \App\User::all();
    return view('pages.create', compact('users'));
}


public function store(Request $request)
{
    $validator = \Validator::make($request->all(), [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required',

    if ($validator->fails())
    {
        return response()->json(['errors'=>$validator->errors()->all()]);
    }
    else
    {
        $users = new User();
        $users->first_name = $request->first_name;
        $users->last_name=$request->last_name;
        $users->email=$request->email;

        $users->save();

        return view('pages.index'); 
    }
}

index.blade.view

          <tbody>
            @foreach($users as $user)
            <tr>
                <td scope="row">{{$user->id}}</td>
                <td>{{$user->first_name.' '.$user->last_name}}</td>
                <td>{{$user->email}}</td>
            </tr>
            @endforeach
          </tbody>
1
  • You're not passing $users into the blade on the store method. Commented Jun 16, 2020 at 12:27

1 Answer 1

1

You should be redirecting to the index route for that resource which returns the index view instead of returning the view itself:

return redirect()->route('pages.index');

I am not sure what your route is named or what the URL is, but what ever the route that points to the index method on your UserController is what you want to redirect to.

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

1 Comment

Thank you so much @lagbox i was missing such a stupid thing

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.