I have a Region
model that has a relationship with my User
model. I need a user to select which region they are in when registering. I'm getting an Undefined variable $regions
error.
RegisterUserController.php
...
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'company_name' => ['required', 'string', 'unique:tenants,name'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$tenant = Tenant::create([
'name' => $request->company_name,
]);
$user = User::create([
'region_id' => $request->region_id,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'role' => 'admin',
'password' => Hash::make($request->password),
'tenant_id' => $tenant->id,
]);
$user->sendEmailVerificationNotification();
event(new Registered($user));
Auth::login($user);
$regions = Region::all();
return redirect(RouteServiceProvider::HOME, compact('regions'));
}
}
register.blade
...<!-- Region -->
<div >
<select wire:model="region_id" id="region_id" name="region_id"
>
<option>Choose Region</option>
@foreach($regions as $reg)
<option value="{{$reg->id}}">{{$reg->region_name}}</option>
@endforeach
</select>
</div>
...
CodePudding user response:
Redirect parameters are used to represent the parameters in the route URL
for example
// For a route with the following URI: profile/{id}
return redirect()->route('profile', ['id' => 1]);
for passing data at redirection you can use with
return \Redirect::route(RouteServiceProvider::HOME)->with(['regions'=>$regions]);
and in blade or controller you can access data using Session::get('regions')
...<!-- Region -->
<div >
<select wire:model="region_id" id="region_id" name="region_id"
>
<option>Choose Region</option>
@if(session()->has('regions'))
@foreach(session()->get('regions') as $reg)
<option value="{{$reg->id}}">{{$reg->region_name}}</option>
@endforeach
@endif
</select>
</div>
...
https://laravel.com/docs/9.x/redirects#redirecting-with-flashed-session-data
CodePudding user response:
You'll want to pass your regions from the controller action that renders the view instead:
public function create()
{
return view('auth.register', [
'regions' => Region::all(),
]);
}