I am adding few new fields to my registration form. All the default field are stored in database except custom field.
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'company_name' => 'required',
]);
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'company_name' => $data['company_name'],
'role' => 'client',
]);
return $user;
}
Here is my form
<form action="/register" method = "post" id = "reg_form">
{{csrf_field()}}
<div class="form-group">
<input type="text" name="name" id="name" placeholder="Name"/>
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email"/>
</div>
<div class="form-group">
<input type="text" name="company_name" id="email" placeholder="Name of your Company"/>
</div>
<div class="form-group">
<input type="password" name="password" id="pass" placeholder="Password"/>
</div>
<div class="form-group">
<input type="password" name="password_confirmation" id="re_pass" placeholder="Re enter password"/>
</div>
<div class="form-group">
<input type="submit" class="btn" id="register_sbt_btn" value="Register"/>
</div>
</div>
</form>
The company_name and role doesn't get stored. I am giving a default value to the role => client whenever a new user registers.
Remember to add the fields on $fillable attribute of User model
protected $fillable = [
'name',
'email',
'password',
'company_name', //<--- HERE
'role', //<--- HERE
];
Also make sure that you have those fields on Users table
Related
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
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'));
}
}
i have 1 form and i want to insert it in 2 table
this is my form
<form action="{{route('dealers.store')}}" method="post">
#csrf
<input class="text email" type="text" name="name" placeholder="Full Name" required="">
<input class="text email" type="text" name="name_of_firm" placeholder="Firm Name" required="">
<input class="text email" type="text" name="number" placeholder="Mobile Number" required="">
<input class="text email" type="text" name="address" placeholder="Address" required="">
<input class="text email" type="email" name="email" placeholder="Email" required="">
<input class="text" type="password" name="password" placeholder="Password" required="">
<input class="text w3lpass" type="password" name="password" placeholder="Confirm Password" required="">
{{-- <div class="wthree-text">
<label class="anim">
<input type="checkbox" class="checkbox" required="">
<span>I Agree To The Terms & Conditions</span>
</label>
<div class="clear"> </div>
</div> --}}
<input type="submit" value="Submit" name="submit">
</form>
this is my DealerController store function where i seperate the data to insert in 2 different table
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
'name_of_firm' => 'required',
'address' => 'required',
'number' => 'required',
]);
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('price'),
'password' => $request->input('detail'),
]);
$dealer = Dealer::create([
'name_of_firm' => $request->input('name_of_firm'),
'address' => $request->input('address'),
'number' => $request->input('number'),
]);
return redirect()->route('admin/charts')->withSuccess('Done');
}
this is my Dealer model where is a relation with user table
use HasFactory;
protected $table = 'dealers';
public function user() {
return $this->belongsTo(User::class);
}
and this is my User model it is package of jetstream
public function dealer() {
return $this->hasMany(Dealer::class);
}
In your controller you're saving the info from the User like this:
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('price'),
'password' => $request->input('detail'),
]);
But there is a request there that makes no sense. In the email you are trying to save the info from an input with the name "PRICE", but that input doesn't exist on your form. The same case applies to the password. That's the source of the error, your are tying to save a null value (since price doesn't exist on the request) to the email column. Try this:
use Illuminate\Support\Facades\Hash;
[....]
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password')),
]);
Note how on the password I added Hash. This encrypts the password to store it securely on your database. If you want to just save the text without that type of security refrain from using Hash.
Here when i fill field with wrong data at time this code give errors but old input not showing. Is there any solution ??
{{ old('name') }} is working but i wanna do with withinput function.
My Controller :-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Userlist;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
class UserlistController extends Controller
{
public function index(){
return view('Project01.index');
}
public function store(Request $request){
$Validator = $request->validate([
'username' => 'required|unique:userlists,username|max:20',
'email' => 'required|email|unique:userlists,email|max:20',
'password' => 'required',
'bod' => 'required',
'comments' => 'required',
'Phone_no' => 'required',
'gender' => 'required',
'agreement' => 'required',
],[
'username.required' => 'Please Enter Your Username',
'email.required' => 'Please Enter Your Username',
'password.required' => 'Please Enter Your Username',
'bod.required' => 'Please Enter Your Username',
'comments.required' => 'Please Enter Your Username',
'Phone_no.required' => 'Please Enter Your Username',
]);
if($Validator->fails()){
return Redirect::back()->withErrors($Validator)->withInput();
}
}
}
Index.blade.php Page
#extends('Structure.main2')
#push('Extra-Header-Links')
<title>Project Index Page</title>
<style type="text/css">
.error-msg{
color: red !important;
}
</style>
#endpush
#section('main-content')
<div class="container">
<div class="col-lg-12 text-center mt-3 mb-3 border-bottom" >
<h1>Project01 Index</h1>
</div>
</div>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-8 mb-5">
<form method="POST" action="{{ route('store') }}">
#csrf
<div class="form-group">
<label for="UserName"><b>UserName</b></label>
<input type="text" name="username" class="form-control" id="UserName" value="">
#error('username')
{{ $errors->first('username') }}
#enderror
</div>
<div class="form-group">
<label for="exampleInputEmail1"><b>Email address</b></label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" >
#if($errors->has('email'))
<small class="form-text text-muted error-msg"> {{ $errors->first('email') }} </small>
#endif
</div>
<div class="form-group">
<label for="exampleInputPassword1"><b>Password</b></label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password">
</div>
<div class="form-group">
<label for="bod"><b>Birth Of Date</b></label>
<input type="date" class="form-control" id="bod" name="bod">
</div>
<div class="form-group">
<label for="comments"><b>Comments</b></label>
<textarea name="comments" class="form-control" id="comments" cols="30" rows="5"></textarea>
</div>
<div class="form-group">
<label for="Phone_no"><b>Phone No</b></label>
<input type="number" class="form-control" name="Phone_no" id="phone_no">
</div>
<div class="form-group">
<label ><b>Gender :- </b></label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="inlineradio1" value="option1" checked>
<label class="form-check-label" for="inlineradio1">Male</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="inlineradio2" value="option2">
<label class="form-check-label" for="inlineradio2">Female</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="inlineradio3" value="option3">
<label class="form-check-label" for="inlineradio3">Other</label>
</div>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" value="1" name="agreement">
<label class="form-check-label" for="exampleCheck1">Accept All Conditions</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
#endsection
#push('Extra-Footer-Scripts')
#endpush
Route:-
Route::prefix('project01')->group(function (){
Route::get('/', 'UserlistController#index');
Route::post('create', 'UserlistController#store')->name('store');
});
Please let me know if anyone know solution of this issue. i do not know why this not working for me.
pass argument to withInput() $request->all() like this
return Redirect::back()->withErrors($Validator)->withInput($request->all());
$Validator = $request->validate([
'username' => 'required|unique:userlists,username|max:20',
'email' => 'required|email|unique:userlists,email|max:20',
'password' => 'required',
'bod' => 'required',
'comments' => 'required',
'Phone_no' => 'required',
'gender' => 'required',
'agreement' => 'required',
],[
'username.required' => 'Please Enter Your Username',
'email.required' => 'Please Enter Your Username',
'password.required' => 'Please Enter Your Username',
'bod.required' => 'Please Enter Your Username',
'comments.required' => 'Please Enter Your Username',
'Phone_no.required' => 'Please Enter Your Username',
]);
$validator->validate();
Try this
use Validator to handle errors - check this - LINK
use Validator;
$validator = Validator::make($request->all(),[
'username' => 'required|unique:userlists,username|max:20',
'email' => 'required|email|unique:userlists,email|max:20',
'password' => 'required',
'bod' => 'required',
'comments' => 'required',
'Phone_no' => 'required',
'gender' => 'required',
'agreement' => 'required',
],[
'username.required' => 'Please Enter Your Username',
'email.required' => 'Please Enter Your Username',
'password.required' => 'Please Enter Your Username',
'bod.required' => 'Please Enter Your Username',
'comments.required' => 'Please Enter Your Username',
'Phone_no.required' => 'Please Enter Your Username',
]);
if($validator->fails()){
return Redirect::back()->withErrors($validator)->withInput();
}
EDITED
if($validator->fails()){
return Redirect::back()->withErrors($validator)->withInput($request->all());
//change order if not work above
//return Redirect::back()->withInput($request->all())->withErrors($validator);
}
If I change just the user table items it'll update them (if i change everything in the user table rows). However, it'll only update the user_infos table when I edit everything.
ProfilesController.php
public function update(Request $request)
{
$user_id = Auth()->user()->id;
$id = Auth()->user()->id;
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'type' => 'required|string',
'description' => 'string',
'projects' => 'string',
'experience' => 'string',
'links' => 'string',
'status' => 'string'
));
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 260)->save( public_path('/images/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
$user = User::find($id);
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $request->input('email');
$user->type = $request->input('type');
$user_info = User_Info::find($user_id);
//$user_info = User_Info::where('user_id', $user->id)->first();
$user_info->description = $request->input('description');
$user_info->projects = $request->input('projects');
$user_info->experience = $request->input('experience');
$user_info->links = $request->input('links');
$user_info->status = $request->input('status');
$user->save();
$user_info->save();
return redirect()->route('profile')->withUser($user);
}
settings.blade.php
<div class="twelve wide column">
<div class="ui segment" data-tab="bio">
<form action="{!! action('ProfilesController#update', ['id' => $user->id]) !!}" method="POST" enctype="multipart/form-data" class="ui form">
{{ csrf_field() }}
<h3>Name</h3>
<div class="inline fields">
<div class="eight wide field">
<input type="text" name="first_name" placeholder="First Name" value="{{ $user->first_name }}">
</div><!-- ./Eight Wide Field -->
<div class="eight wide field">
<input type="text" name="last_name" placeholder="Last Name" value="{{ $user->last_name }}">
</div> <!-- ./Eight Wide Field -->
</div><!-- ./Inline Fields -->
<h3 class="header">Profile Image</h3>
<div class="inline fields">
<div class="sixteen wide field">
<input type="file" name="avatar">
</div> <!-- ./Sixteen Wide Field -->
</div> <!-- ./Inline Fields -->
<h3 class="header">Email</h3>
<div class="inline fields">
<div class="sixteen wide field">
<input type="email" name="email" placeholder="Email" value="{{ $user->email }}">
</div> <!-- ./Sixteen Wide Field -->
</div> <!-- ./Inline Fields -->
<h3>Type</h3>
<div class="inline fields">
<div class="sixteen wide field fluid">
<select name="type" class="ui dropdown fluid registerType">
<option value="Developer">Developer</option>
<option value="Designer">Designer</option>
<option value="Fullstack">FullStack</option>
<option value="Client">Client</option>
</select>
</div> <!-- ./Sixteen Wide Field Fluid -->
</div><!-- ./Inline Fields -->
<h3 class="header">Description</h3>
<textarea name="description" id="" cols="30" rows="10" placeholder="Description">{{ isset($user->userInfo->description) ? $user->userInfo->description : "This User Has No Description" }}</textarea>
<h3 class="header">Projects</h3>
<textarea name="projects" id="" cols="30" rows="3" placeholder="Projects">{{ isset($user->userInfo->projects) ? $user->userInfo->projects : "This User Has No Projects Listed" }}</textarea>
<h3 class="header">Experience</h3>
<textarea name="experience" id="" cols="30" rows="3" placeholder="Experience">{{ isset($user->userInfo->experience) ? $user->userInfo->experience : "This User Has No Experience Listed" }}</textarea>
<h3 class="header">Links</h3>
<input type="text" name="links" placeholder="Links" value="{{ isset($user->userInfo->links) ? $user->userInfo->links : "This User Has No Links Listed" }}">
<h3 class="header">Status</h3>
<input type="text" name="status" placeholder="Status" value="{{ isset($user->userInfo->status) ? $user->userInfo->status : "Available" }}">
<br><br>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="ui medium fluid blue button" value="Update">
{!! Form::close() !!}
</div><!-- ./Ui Segment -->
</div> <!-- ./Twelve Wide Column -->
Thanks in advance!
Using: Laravel 5.4
In here:
$user->update(); // <--- try this
$user->save();
$user_info->save();
In my ProfilesController.php I had to change the validation for "email" inside public function update(Request $request) a little bit.
From:
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'type' => 'required|string',
'description' => 'string',
'projects' => 'string',
'experience' => 'string',
'links' => 'string',
'status' => 'string',
));
To:
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$id,
'type' => 'required|string',
'description' => 'string',
'projects' => 'string',
'experience' => 'string',
'links' => 'string',
'status' => 'string',
));