I'm using this code for User Sign Up in Laravel:
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'phone' => $validatedData['phone'],
'type' => $validatedData['type'],
'verified' => $validatedData['verified'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->accessToken;
return response()->json([
'user' => $user,
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
As you can see , some of my field are unique , so I want to display a message in my front side that displays the error from the back side.
Exemple : When a user enters a used phone number , I want to return an error saying : this phone number has been used .
How can I achieve this ? Thank you.
You can get a User record from the database by phone. If the record exists, then do your logic
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
// get a user record by phone
$record = User::where('phone', $validatedData['phone'])->find();
if (!empty($record)) {
return response()->json([
'error' => 'this phone number has been used'
])
}
//.....
}
So, I'm trying to make update function, using this
public function editProfile(Request $request, $id)
{
// Validating
$request->validate([
// 'username' => 'nullable|unique:users|min:4',
// 'email' => 'nullable|unique:users|email:rfc,dns',
'contact_phone' => 'nullable|digits_between:9,12',
'bio_en' => 'nullable',
'bio_ar' => 'nullable',
'icon' => 'nullable',
'logo' => 'nullable',
'plan_id' => 'required',
'category_id' => 'required',
'is_local' => 'required',
]);
$user = User::find($id);
$user->update([
'username' => $request->username,
'email' => $request->email,
'contact_phone' => $request->contact_phone,
'bio_en' => $request->bio_en,
'bio_ar' => $request->bio_ar,
'logo' => $request->logo,
'icon' => $request->icon,
'plan_id' => $request->plan_id,
'category_id' => $request->category_id,
'referred_by_id' => Auth::user()->id,
]);
if ($user) {
return back()->with("success", __("editedSuccessfully"));
} else {
return back()->with('error', __("somethingWentWrongTryAgainLater"));
}
}
but I get the error
Call to a member function update() on null
shows on line $user->update
hope anyone can help me
It returns null because it cannot find the user with User::find($id). Check that you have a user by $id
ok, I'm trying to login the users after success registration into their panels. the database line built successfully. but alternately user login become successful but once not.
Here is the Request Controller Code:
$request->merge(['phone'=> '09123456789']);
$request->merge(['name' => 'User']);
$request->merge(['password' => 'pass123456789']);
$request->merge(['email' => 'user#email.com']);
$credentials = $request->validate([
'name' => 'required',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required',
'email' => 'required',
]);
User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $credentials['phone'],
'password' => Hash::make($credentials['password'])
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->route('panel');
}
The Model:
protected $fillable = [
'name',
'phone',
'email',
'password',
];
let me know if I didn't describe perfectly
First, I would stop using validation in the controller and use form request validation instead. It's been the standard since Laravel 5.
Try this simplified code using Auth::login() instead:
public function createUser(Request $request)
{
$request->validate([
'name' => 'required|string|max:64',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required|string|max:64',
'email' => 'required|email|max:64',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'password' => Hash::make($request->password),
]);
Auth::login($user);
return redirect()->route('panel');
}
I'm making an app that runs like google form using Laravel 5.7. Here is the form table that i already made:
I made an eloquent model so that each Name in Personal details table has one record that contains all these table and insert filled table into database after click submit button. The problem is, it didn't successfully inserted into database. I don't know what's the problem, here are my codes:
PersonalDetails.php (eloquent model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonalDetails extends Model
{
protected $table = 'personal_details';
protected $guarded = ['id'];
public function accomodation()
{
return $this->hasOne('App\Accomodation');
}
public function course()
{
return $this->hasOne('App\Course');
}
public function proposedStudy()
{
return $this->hasOne('App\ProposedStudy');
}
public function emergencyContact()
{
return $this->hasOne('App\EmergencyContact');
}
public function englishTestResult()
{
return $this->hasOne('App\EnglishTestResult');
}
public function homeInstitution()
{
return $this->hasOne('App\HomeInstitution');
}
public function insurance()
{
return $this->hasOne('App\Insurance');
}
}
FormController.php
public function submit(Request $request) {
$request->validate([
// Personal Details
'fullname' => 'required|string',
'nationality' => 'required|string',
'date_of_birth' => 'required|string',
'passport_number' => 'required|string',
'issuing_country' => 'required|string',
'date_of_issue' => 'required|string',
'date_of_expiry' => 'required|string',
'blood_type' => 'required|string',
'marital_status' => 'required|string',
'address' => 'required|string',
'city' => 'required|string',
'postal_code' => 'required|numeric',
'province' => 'required|string',
'country' => 'required|string',
'phone' => 'required|string',
'mobile' => 'required|string',
'email' => 'required|email',
'address2' => 'nullable|text',
'city2' => 'nullable|string',
'postal_code2' => 'nullable|numeric',
'province2' => 'nullable|string',
'country2' => 'nullable|string',
'phone2' => 'nullable|string',
'contact_name' => 'required|string',
// Home Institution
'name' => 'required|string',
'address' => 'required|string',
'phone' => 'required|string',
'email' => 'required|email',
'website' => 'required|string',
'faculty_dep' => 'required|string',
'start_year' => 'required|string',
'gpa' => 'required|string',
// Proposed Study
'semester' => 'required|in:Semester I (Aug-Jan),Semester II (Feb-Jun)',
'academic_year' => 'required|string',
'faculty' => 'required|string',
'department' => 'required|string',
'study_period' => 'required|string',
'start_date' => 'required|string',
'end_date' => 'required|string',
// Course
'course_title' => 'required|string',
'credit' => 'required|string',
// English Test Result
'test' => 'required|string',
'score' => 'required|numeric',
'test_center' => 'required|string',
'date_tested' => 'required|string',
// Insurance
'insurance_name' => 'required|string',
'validity' => 'required|string',
'cover' => 'required|string',
// Accomodation
'accomodation_help' => 'required|in:YES,NO',
'adress' => 'required|string',
'contact_person' => 'required|string',
// Contact of Emergency
'fullname' => 'required|string',
'relationship' => 'required|string',
'address' => 'required|string',
'phone' => 'required|string',
'mobile' => 'required|string',
'email' => 'required|email',
]);
PersonalDetails::create([
'fullname' => $request->input('name'),
'nationality' => $request->input('nationality'),
'date_of_birth' => $request->input('dob'),
'passport_number' => $request->input('passport'),
'issuing_country' => $request->input('is_country'),
'date_of_issue' => $request->input('doi'),
'date_of_expiry' => $request->input('doe'),
'blood_type' => $request->input('blood'),
'marital_status' => $request->input('maritial'),
'address' => $request->input('address'),
'city' => $request->input('city'),
'postal_code' => $request->input('postal'),
'province' => $request->input('state'),
'country' => $request->input('country'),
'phone' => $request->input('phone'),
'mobile' => $request->input('mobile'),
'email' => $request->input('email'),
'address2' => $request->input('address2'),
'city2' => $request->input('city2'),
'postal_code2' => $request->input('postal2'),
'province2' => $request->input('state2'),
'country2' => $request->input('country2'),
'phone2' => $request->input('phone2'),
'contact_name' => $request->input('contact_name'),
]);
HomeInstitution::create([
'name' => $request->input('institution'),
'address' => $request->input('i_address'),
'phone' => $request->input('i_phone'),
'email' => $request->input('i_email'),
'website' => $request->input('web'),
'faculty_dep' => $request->input('faculty_dept'),
'start_year' => $request->input('s_year'),
'gpa' => $request->input('gpa'),
]);
ProposedStudy::create([
'semester' => $request->input('duration'),
'academic_year' => $request->input('f_year') . '/' . $request->input('l_year'),
'faculty' => $request->input('faculty'),
'department' => $request->input('department'),
'study_period' => $request->input('spesific_period'),
'start_date' => $request->input('start_date'),
'end_date' => $request->input('end_date'),
]);
Course::create([
'course_title' => $request->input('course_1'),
'credit' => $request->input('credit_1'),
]);
EnglishTestResult::create([
'test' => $request->input('toefl'),
'score' => $request->input('score_toefl'),
'test_center' => $request->input('place_toefl'),
'date_tested' => $request->input('date_toefl'),
]);
Insurance::create([
'insurance_name' => $request->input('insurance'),
'validity' => $request->input('valid_date'),
'cover' => $request->input('cover'),
]);
Accomodation::create([
'accomodation_help' => $request->input('opt_acc'),
'adress' => $request->input('adress_acc'),
'contact_person' => $request->input('cp_acc'),
]);
EmergencyContact::create([
'fullname' => $request->input('emergency_name'),
'relationship' => $request->input('relationship'),
'address' => $request->input('address_emergency'),
'phone' => $request->input('emergency_phone'),
'mobile' => $request->input('emergency_mobile'),
'email' => $request->input('emergency_email'),
]);
// return back()-> with('success', 'Berhasil submit!');
}
Finally after all these struggles to figured out the problem, i just realized that i put wrong name in validation rules. The name on the left side of validation rules is different with name in html so i reformed the name in html and validation rules.
The big deal is i didn't put any validation error message after submit so that it won't inserted into database. After i put some error message, all of the field returned error that says "The :attribute is required". Simply because the name in validation is different with the html name :D
Thank you guys for helped me to figured out the problem, i worked it out :))
try with model path,if model folder is inside App then App\model;
eg:-
App\Insurance::create([
'insurance_name' => $request->input('insurance'),
'validity' => $request->input('valid_date'),
'cover' => $request->input('cover'),
]);
add $fillalbe in Model:
protected $fillable=['full_name','nationality','...']
you will need to specify fillalbe attribute on the model. read more at https://laravel.com/docs/5.7/eloquent#mass-assignment
Can you check your table migration or model relation, then revision your form controller.
I am create example from your code and successfull insert into database.
Personal Details Migration
Schema::create('personal_details', function (Blueprint $table) {
$table->increments('id');
$table->string('fullname')->nullable();
$table->string('nationality')->nullable();
$table->timestamps();
});
Home Institution Migration
Schema::create('home_institution', function (Blueprint $table) {
$table->integer('personal_details_id')->unsigned()->primary();
$table->string('name')->nullable();
$table->string('address')->nullable();
$table->timestamps();
#Foreign to Table Personal Details.
$table->foreign('personal_details_id')->references('id')->on('personal_details')->onUpdate('cascade')
->onDelete('cascade');
});
Personal Detail Model Relation
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonalDetails extends Model
{
protected $guarded = ['id'];
public function homeInstitution()
{
return $this->hasOne('App\HomeInstitution');
}
# Other your Relation
}
Form Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PersonalDetails;
class FormController extends Controller
{
public function index()
{
return view('form.index');
}
public function submit(Request $request)
{
$request->validate([
// Personal Details
'fullname' => 'required|string',
'nationality' => 'required|string',
// Home Institution
'name' => 'required|string',
'address' => 'required|string',
]);
$pd = PersonalDetails::create(
['fullname' => $request->get('fullname'), 'nationality' => $request->get('nationality')]
);
# Insert into HomeInstitution => base on Model Relation from PersonalDetails
$pd->homeinstitution()->create(
['name' => $request->get('name'), 'address' => $request->get('address')]
);
# Insert into other youR relation
/*$pd->example()->create(
[]
);*/
return dd('Successfull Insert');
}
}
Maybe its can help you.
I have two different routes:
Route::post('contact', 'PublicController#postContact');
Route::post('inquiry', [ 'as' => 'inquiry', 'uses' => 'PublicController#postInquiry']);
and their methods:
public function postContact(Request $request){
$token = $request->input('g-recaptcha-response');
if (strlen($token) >0 ) {
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'phone' => 'required',
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min:10']);
$data = array(
'fname' => $request->fname,
'lname' => $request->lname,
'phone' => $request->phone,
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
Mail::send('emails.contact', $data, function($message) use ($data){
$message->from($data['email']);
$message->to('rahunn3#gmail.com');
$message->subject($data['subject']);
});
Session::flash('success', 'Your Email was sent sucessfully!');
return redirect('/contact');
}
}
and:
public function postInquiry(Request $request){
$token = $request->input('g-recaptcha-response');
if (strlen($token) >0 ){
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'phone' => 'required',
'country' => 'required',
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min:10']);
$data = array(
'fname' => $request->fname,
'lname' => $request->lname,
'phone' => $request->phone,
'country' => $request->country,
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
Mail::send('emails.inquiry', $data, function($message) use ($data){
$message->from($data['email']);
$message->to('rahunn3#gmail.com');
$message->subject($data['subject']);
});
Session::flash('success', 'Your Email was sent sucessfully!');
return view('public.pages.thankyou');
}
}
the trouble i'm having is the second method is not working as it should be.The inquiry form is in view(single.blade.php). After sumbitting the form user should be redirected to view(thankyou.blade.php) view but it is redirecting to view(single.blade.php) without sending email and doesn't show any errors.
If I remove the validation part:
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'phone' => 'required',
'country' => 'required',
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min:10'
]);
from the second method postInquiry it works perfectly(sends email and redirects do thankyou.blade.php)
Can anyone tell me what wrong I am doing here ?
It is redirecting because your validation is failing.
Add the following code to the top of your single.blade.php file and it will tell you why the validation is failing
#if($errors->has())
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
#endif
See here for more information : https://laravel.com/docs/5.3/validation#quick-displaying-the-validation-errors