phplaravelcontrollerresourcesundefined-variable

Undefined variable:users.....Variable conflict when using a resource controller index and store method in laravel


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>

Solution

  • 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.