How can I pre-fill form data entered by a user in Laravel 7 - laravel

I'm making a registration form where users will be redirected to a preview page to confirm their details first before submitting the form. I'm using Laravel 7 and I'm quite new to Laravel. Once the user enters their details in registration form, the same details will be pre-filled in the preview form before submission. I have tried some code in my controller but it's giving me an error Trying to get property 'myForm' of non-object In my Controller, $data is an array, I'm not sure how I can achieve this. Please help.
In my Conroller:
public function confirmation(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data['myForm'] = $request->all();
return view('auth.client.preview', compact('categories', 'data'));
}
In my blade view:
<div class="form-group">
<label for="first_name">First Name</label><span class="text-danger">*</span>
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
<div class="invalid-feedback">
{{ $errors->first('first_name') }}
</div>
</div>
My Route:
Route::post('/preview-details', 'Auth\Client\PreviewRegisterDetailsController#confirmation')->name('preview-details');
Dropdown List:
<label for="fundi_type">Fundi Type</label><span class="text-danger">*</span>
<select class="custom-select" id="category_id" name="category_id">
#foreach($categories as $category )
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>

Simplify like this below .So no need to create extra array key .
$myForm = $request->all();
return view('auth.client.preview', compact('categories', 'myForm'));
and in view
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Updated
<option value="{{ $category->id }}" {{($myForm['category_id']==$category->id)?'selected':null}}>{{ $category->name }}</option>

Edit your blade file code.
Actually your controller is sending array and you are accessing that array as a collection.
From :
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
To
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data['myForm']['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Hope this will be useful.

Related

error message not appearing, validate array

Please help me showing my error message, array message not appears in table
$validation_file = $this->validate([
'requirements' => 'required|array',
'requirements.*' => 'required|array',
'requirements.*.file' => 'required|mimes:pdf,jpg,png,jpeg|max:20000|array',
'input.*.input' => 'required|array',
'requirements.*.file.input' => 'required|array',
]);
Blade
<input type="hidden" name="req_id[{{ $key }}]" wire:model="req_id.{{ $key }}.id" value="{{ $requirements->id }}">
<input type='file' wire:model="requirement.{{ $requirements->id }}.file" class="form-control" accept=".pdf">
#error('requirements.{{ $key }}.file')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
<input type="hidden" name="req_id[{{ $key }}]" wire:model="req_id.{{ $key }}.id" value="{{ $input->id }}">
<input type='text' wire:model.defer="input.{{ $input->id }}.input" class="form-control">
#error('input.{{ $key }}.input')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
Your wire:model has a spelling error:
wire:model="requirement.{{ $requirements->id }}.file"
It should be (notice the missing s):
wire:model="requirements.{{ $requirements->id }}.file"

Check dynamic variable of an array contains value or not in php

This is my basic form to create contacts in create.vue --
<div class="form-group mb-3 ">
<label class="form-label">Name</label>
<div>
<input type="text" class="form-control" placeholder="Enter Name" v-model="form.name" required>
</div>
</div>
<div class="form-group mb-3 ">
<label class="form-label">Contact Id</label>
<div>
<input type="text" class="form-control" placeholder="Enter Contact Id" v-
model="form.contact_id" required>
</div>
</div>
then I am giving the option to add address in the same form but which is not required. but if USER wants, while creating contact , user can add multiple addresses as well.
<div class="form-group row" v-for="(item, k) in form.addresses" :key="k" >
<label for="exampleFormControlInput1" class="form-label">Street 1:</label>
<div class="form-group mb-3">
<input class="form-control" type="text" v-model="item.street1" name="street1"
placeholder="Enter Street 1">
</div>
<div class="form-group mb-3">
<label for="exampleFormControlInput1" class="form-label">State</label>
<select class="form-control" v-model="item.state_id" name="state_id">
<option value="">Choose State</option>
<option value="1">Manitoba</option>
<option value="2">Winnipeg</option>
<option value="3">Punjab</option>
<option value="4">Other</option>
</select>
</div>
<div class="form-group mb-3">
<label for="exampleFormControlInput1" class="form-label">Country</label>
<select class="form-control" v-model="item.country_id" name="country_id">
<option value="">Choose Country</option>
<option value="1">Canada</option>
<option value="2">U.S</option>
<option value="3">India</option>
<option value="4">Other</option>
</select>
</div>
<div class="form-group mb-3">
<button class="btn btn-sm btn-danger" type="button"
#click="removeAddress(k)">Remove</button>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<input class="btn btn-primary form-control" type="button" value="Add Another Address"
#click="addAddress()">
</div>
</div>
But whenever i am storing the data in database, it should be stored if only name has been given .
In the controller, my data is being fetched like this if i use return $request->all()--
{"name":"y","contact_id":"y","addresses":"[{"street1":"y","state_id":"1","country_id":"1"}]"}
Below is my controller code --
public function store(Request $request)
{
//return $request->all();
$contact = Contacts::create([
'name' => $request->name,
'company_id' => Auth::user()->company_id,
]);
$addresses= json_decode($request->addresses, true);
//return $addresses;
//[{"street1":"","state_id":"","country_id":""}]
if (! empty($addresses)) {
foreach($addresses as $ad) {
$address = new Address;
$address->contact_id = $contact->id;
$address->street1 = $ad['street1'];
$address->state_id = $ad['state_id'];
$address->country_id = $ad['country_id'];
$address->save();
}
}
how to check if variable values of street, state and country is null, it should not store data.
It is returning me error
Invalid datetime format: 1366 Incorrect integer value: '' for column clientchief_db.addresses.state_id at row 1 (SQL: insert into addresses (contact_id, street1, state_id, country_id, updated_at, created_at) values (14, , , , 2022-06-14 19:26:49, 2022-06-14 19:26:49))"
You should validate your request:
$request->validate([
'addresses' => ['required', 'array'],
'addresses.*.street1' => ['required', 'string'],
'addresses.*.state_id' => ['required', 'numeric'],
'addresses.*.country_id' => ['required', 'numeric'],
]);
If I understand it right
User can fill up just name & submit the form - data should be persisted in the database
User can fill up multiple address, but if user doesn't fill up complete details (street, state & country should be filled) for the address it should not be persisted in the database
One approach would be to
validate the address data, ONLY if user added address to the form
and return validation error if street1, state_id or country_id is null
public function store(Request $request)
{
//return $request->all();
$validated = $request->validate([
'name' => ['required', 'string'],
'addresses' => ['sometimes', 'array'],
'addresses.*.street1' => ['sometimes', 'required', 'string'],
'addresses.*.state_id' => ['sometimes', 'required', 'numeric'],
'addresses.*.country_id' => ['sometimes', 'required', 'numeric'],
]);
//The above will pass validation if name is filled as non empty string & addresses is not present in the request data
//But if the addresses is present in the request, it will fail if either of street1, state_id or country_id is null
$contact = Contacts::create([
'name' => $request->name,
'company_id' => Auth::user()->company_id,
]);
$addresses= json_decode($request->addresses, true);
//return $addresses;
//[{"street1":"","state_id":"","country_id":""}]
if (! empty($addresses)) {
foreach($addresses as $ad) {
$address = new Address;
$address->contact_id = $contact->id;
$address->street1 = $ad['street1'];
$address->state_id = $ad['state_id'];
$address->country_id = $ad['country_id'];
$address->save();
}
}
//return response
}
Laravel Docs - Validation - Validating When Present

How can I solve 404 errors in Laravel 7?

I'm making a registration form using Laravel 7, my form has a "preview" step where users first check the details and either submit the details as they are or edit. The actual submission of the details happens in the blade file named preview.blade.php and this is where I have placed the form action for posting the data. This part works well, the edit part is the one with the problem as it gives 404 error. Please help.
In my register.blade.php:
<form method="post" action="{{ url('/preview-details') }}" id="regForm">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my preview.blade.php:
<div>
<a href="{{route('edit_preview')}}">
<button type="button" class="btn btn-primary btn-sm"
style="float:right;"><i class="fas fa-edit"> </i>Edit</button>
</a>
</div>
<form method="post" action="{{ url('/client-registration') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my edit_preview.php (this one shows 404 error):
<form method="post" action="{{ url('/client-registration') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my Routes file:
Route::get('/client-registration', 'Auth\Client\RegisterController#create')->name('client-registration');
Route::post('/client-registration', 'Auth\Client\RegisterController#store');
Route::post('/preview-details', 'Auth\Client\PreviewRegisterDetailsController#confirmation')->name('preview-details');
Route::post('/preview-details-existing', 'Auth\Client\PreviewDetailsExistingClientController#confirmation')->name('preview-existing');
Route::post('/edit_preview', 'Auth\Client\EditRegisterDetailsController#editDetails')->name('edit_preview');
In my Preview Controller (It works well):
class PreviewRegisterDetailsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
// Validating the User
public function confirmation(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data = $request->all();
return view('auth.client.preview', compact('categories', 'data'));
}
}
In my edit details controller:
class EditRegisterDetailsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
// Validating the User
public function editDetails(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data = $request->all();
return view('auth.client.edit_preview', compact('categories', 'data'));
}
}

Laravel validation with create form: retrieve old input data for dropdown box

I have a Laravel application which uses a form to create items. The form uses validation as defined in the Laravel documentation under this section.
I have a StoreItem Request file:
public function rules() {
return [
'item_name'=>'required',
'category_id'=> 'required',
'collection_id'=> 'required',
'brewery_id'=> 'required',
];
}
and in the controller I have the following:
public function store(storeItem $request)
{
$validated = $request->validated();
$item = new Item([
'user_id' => Auth::id(),
'item_name' => $request->item_name,
'category_id' => $request->category_id,
'collection_id' => $request->collection_id,
'brewery_id' => $request->brewery_id,
]);
$item->save();
When validation is catching an error, the create form is presented again but I don't see the old input data.
For the input text fields, I have done the following:
<input type="text" class="form-control" name="item_name" value="{{ old('item_name') }}" />
and this shows the old input data, but what to do for the dropdown boxes like category_id, collection_id and brewery_id. I want them to have the old value as the 'selected' value.
Currently in the form I have (for the dropdown boxes):
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}">{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
This source seems to indicate that using the old() method might even not be needed, but if I don't use the
You need to manually add the selected attribute to the previously selected value. For example:
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ old("brewery_id") == $brewery->id ? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
try this as well. I've added bracket open and close to (old('brewery_id')==$brewery->id)
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ (old('brewery_id') == $brewery->id)? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>

How to get session mobile in laravel

I want to after registered a user name, age, mobile and ... get the session of mobile because in next page, I want to get mobile in input hidden.
Attention: I did not do session at all.
I think it's like this:
RegisterController.php
public function register(Request $request, User $user)
{
$code = rand(10000,99999);
session->get('mobile')
$user = \App\User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'gender' => $request->gender,
'mobile' => $request->mobile,
'code' => $code,
.
.
.
return redirect()->route('code')->with('mobile', $request->mobile);
}
It redirect to this page.
Code
code.blade.php
<form action="{{ route('send') }}" method="post">
{{ csrf_field() }}
<input type="hidden" class="form-control" value="{{ session->mobile }}" name="mobile" id="mobile">
<div class="form-group">
<label for="code">کد</label>
<input type="text" class="form-control" name="code" id="code">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" id="btn-ok">OK</button>
</div>
</form>
use Illuminate\Support\Facades\Session;
For saving in session use
Session::put('mobile', $request->mobile);
then retrieve it using
Session::get('mobile');

Resources