Problem with Login after register by Laravel - laravel

When I register in laravel ,I can't login by that account.
This is my controller code:
public function register(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'name' => 'required|string|min:3|max:255',
'phone' => 'required|numeric|digits:11|unique:users',
'password' => 'required|string|min:6',
]);
$data = $request->all();
//check unique phone
$usersCount = User::where('phone', $data['phone'])->count();
if ($usersCount > 0) {
return back()->with('flash_message_error', 'این شماره قبلا ثبت شده است');
} else {
$user = new User;
$user->name = $data['name'];
$user->phone = $data['phone'];
$user->password = bcrypt($data['password']);
$user->save();
if (Auth::attempt(['phone' => $data['phone'], 'password' => $data['password']])) {
Session::put('frontSession', $data['phone']);
return redirect('profile');
}
}
}
public function login(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'phone' => 'required|numeric|digits:11',
'password' => 'required|string',
]);
$data = $request->all();
if (Auth::attempt(['phone' => $data['phone'], 'password' => $data['password']])) {
Session::put('frontSession', $data['phone']);
return redirect('/');
} else {
return redirect()->back()->with('flash_message_error', 'Not Valid');
}
}
}
And this is blade:
<form action="{{route('userLogin')}}" name="loginForm" method="POST">
#csrf
<input class="form-control" type="number" id="phone" name="phone" placeholder="phone number"/>
<input class="form-control" type="password" id="password" name="password" placeholder="password"/>
<small style="direction: ltr">
<label for="remember" class="form-check-label">remember me</label>
<input id="remember" class="form-check-input" type="checkbox" class="checkbox">
</small>
<button type="submit" class="btn iren-btn btn-block">login</button>
</form>
<form id="registerForm" name="registerForm" action="{{url('user-register')}}" method="post">
#csrf
<input class="form-control" id="name" name="name" type="text" placeholder="name"/>
<input class="form-control" id="phone" name="phone" type="number" placeholder="phone"/>
<input class="form-control mb-2" id="myPassword"
name="password" type="password" placeholder="password" style="direction: ltr"/>
<button type="submit" class="btn iren-btn btn-block">register</button>
</form>
after login it errors 'Not Valid' because of password.When I change password in database by copying from another field that I created by db:seed, it works.

Replace this
public function login(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'phone' => 'required|numeric|digits:11',
'password' => 'required|string',
]);
$data = $request->all();
if (Auth::attempt(['phone' => $data['phone'], 'password' => $data['password']])) {
Session::put('frontSession', $data['phone']);
return redirect('/');
} else {
return redirect()->back()->with('flash_message_error', 'Not Valid');
}
}
}
with :
public function login(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'phone' => 'required|numeric|digits:11',
'password' => 'required|string',
]);
$data = $request->all();
$user = User::where('phone', $data['phone'])->first();
if ($user) {
if(Hash::check($data['password'], $user->password))
{
Auth::login($user);
Session::put('frontSession', $data['phone']);
return redirect('/');
}
else{
return redirect()->back()->with('flash_message_error', 'password does not match');
}
} else {
return redirect()->back()->with('flash_message_error', 'Not Valid');
}
}
}

Related

Laravel multi select options ajax request

I'm trying to add multiple courses for a user using ajax. When I click on submit button, everything else updated but the courses. I don't know what I did wrong. Please help me...
This is my blade:
<input type="hidden" name="user_id" id="user_id" value="{{$user_details->id}}">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{$user_details->name}}">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="{{$user_details->email}}">
</div>
<div class="form-group">
<label for="courses_id">Courses</label>
#php
$all_courses = $user_details->courses_id;
#endphp
<select name="courses_id[]" multiple id="course" class="form-control nice-select wide">
#foreach($courses as $data)
#if($all_courses)
<option #if(in_array($data->id,$all_courses)) selected #endif value="{{$data->id}}">{{$data->title}}</option>
#else
<option value="{{$data->id}}">{{$data->title}}</option>
#endif
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary mt-4 pr-4 pl-4">{{__('Update User')}}</button>
</form>
<script>
$(document).ready(function() {
if($('.nice-select').length > 0){
$('.nice-select').niceSelect();
}
$(document).on('change','select[name="courses_id[]"]',function (e) {
e.preventDefault();
var selectedId = $(this).val();
$.ajax({
url : "{{route('admin.user.course.by.slug')}}",
type: "POST",
data: {
_token : "{{csrf_token()}}",
id: selectedId
},
success:function (data) {
$('#course').html('');
$.each(data,function (index,value) {
$('#course').append('<option '+selected+' value="'+value.id+'">'+value.title+'</option>');
$('.nice-select').niceSelect('update');
});
}
});
});
} );
</script>
My controller:
namespace App\Http\Controllers;
use App\Courses;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function edit($id)
{
$user_details = User::find($id);
$courses = Courses::where(['status'=> 'publish'])->get();
return view('backend.user.edit-user')->with([ 'user_details' => $user_details, 'courses' => $courses]);
}
public function user_update(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:191',
'email' => 'required|string|max:191',
'courses_id' => 'nullable',
],[
'name.required' => __('Name is required'),
'email.required' => __('Email is required'),
]);
User::find($request->user_id)->update([
'name' => $request->name,
'email' => $request->email,
'courses_id' => serialize($request->courses_id),
]);
return redirect()->back()->with(['msg' => __('User Profile Updated Successfully..'), 'type' => 'success']);
}
public function course_by_slug(Request $request){
$all_courses = Courses::where(['status' => 'publish'])->get();
return response()->json($all_courses);
}
}
My route:
Route::prefix(user')->middleware(['adminPermissionCheck:Users Manage'])->group(function () {
Route::get('/edit/{id}', 'UserController#edit')->name('admin.user.edit');
Route::post('/update', 'UserController#user_update')->name('admin.user.update');
Route::post('/course-by-slug', 'UserController#course_by_slug')->name('admin.user.course.by.slug');
});

Profile Not Updating In Laravel Livewire

I was to create a user profile components that's will allow users to update there account, so i have created the profile update form when I input the new details I'm getting there is no user_id
public $users, $name, $email, $user_id, $creator_name, $creator_bio;
public $updateMode = false;
private function resetInputFields(){
$this->name = '';
$this->email = '';
$this->creator_name = '';
$this->creator_bio = '';
}
public function edit($id)
{
$this->updateMode = true;
$user = User::where('id',$id)->first();
$this->user_id = $id;
$this->name = $user->name;
$this->email = $user->email;
$this->creator_name = $user->creator_name;
$this->creator_bio = $user->creator_bio;
}
public function cancel()
{
$this->updateMode = false;
$this->resetInputFields();
}
public function update()
{
$validatedDate = $this->validate([
'name' => 'required',
'email' => 'required|email',
]);
if ($this->user_id) {
dd('There is a user id');
$user = User::find($this->user_id);
$user->update([
'name' => $this->name,
'email' => $this->email,
]);
$this->updateMode = false;
session()->flash('message', 'Users Updated Successfully.');
$this->resetInputFields();
} else {
dd('There is NOT a user id');
}
}
// public function delete($id)
// {
// if($id){
// User::where('id',$id)->delete();
// session()->flash('message', 'Users Deleted Successfully.');
// }
// }
public function render()
{
return view('livewire.profile-update');
}
here is my profile update form when I click update nothing is happening and I'm passing the livewire script correctly
<div>
<form>
<div class="form-group">
<input type="hidden" wire:model="user_id">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" wire:model="name" id="exampleFormControlInput1" placeholder="Enter Name">
#error('name') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class="form-group">
<input type="hidden" wire:model="user_id">
<label for="exampleFormControlInput1">Creator Name</label>
<input type="text" class="form-control" wire:model="creator_name" id="exampleFormControlInput1" placeholder="Enter Name">
#error('creator_name') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class="form-group">
<input type="hidden" wire:model="user_id">
<label for="exampleFormControlInput1">Creator Bio</label>
<input type="text" class="form-control" wire:model="creator_bio" id="exampleFormControlInput1" placeholder="Enter Name">
#error('creator_bio') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Email address</label>
<input type="email" class="form-control" wire:model="email" id="exampleFormControlInput2" placeholder="Enter Email">
#error('email') <span class="text-danger">{{ $message }}</span>#enderror
</div>
<button wire:click.prevent="update()" class="btn btn-dark">Update</button>
<button wire:click.prevent="cancel()" class="btn btn-danger">Cancel</button>
</form>
</div>
you must implement the fillable or guarded protected property in the User class
protected $fillable = [
'name','email'
];
// or
protected $guarded = [];

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'));
}
}

Total, Quantity, Price in Laravel

I have a table named 'products' with 5 fields (id, title, price, quantity, total).
My goal is to calculate via the form products.create the total, price * quantity.
Database - products
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->integer('quantity');
$table->double('price');
$table->double('total')->nullable();
$table->timestamps();
});
}
Model - product
protected $fillable = ['title', 'quantity', 'price', 'total'];
public function setTotalAttribute()
{
$this->total = $this->quantity * $this->price;
}
public function getTotalAttribute($value)
{
return $value;
}
** Controller - ProductController**
public function index()
{
$products = Product::oldest()->paginate(5);
return view('admin.products.index', compact('products'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
$products = Product::all();
return view('admin.products.create', compact('products'));
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
'total' => 'required'
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success', 'save');
}
My problem is in my view "products.create" I have 3 fields when I encode the 3 fields, nothing happens ???
Products.create
<form class="panel-body" action="{{route('products.store')}}" method="POST" novalidate>
#csrf
<fieldset class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="form-group-input-1">Title</label>
<input type="text" name="title" id="title" class="form-control" value="{{ old('title')}}"/>
{!! $errors->first('title', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('quantity') ? 'has-error' : '' }}">
<label for="form-group-input-1">Quantity</label>
<input type="text" name="quantity" id="quantity" class="form-control" value="{{ old('quantity')}}"/>
{!! $errors->first('quantity', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('price') ? 'has-error' : '' }}">
<label for="form-group-input-1">Price</label>
<input type="text" name="price" id="price" class="form-control" value="{{ old('price')}}"/>
{!! $errors->first('price', '<span class="help-block">:message</span>') !!}
</fieldset>
Back
<button type="submit" class="btn btn-sm btn-primary">Valider</button>
Thank you for help.
First of all you didn't send any total value...
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
]);
Just follow Eloquent ORM
$product = New Product();
$product-title = $request->title;
$product-quantity = $request->quantity;
$product-price = $request->price;
$product-total = $request->price * $request* quantity;
$product->save();
//redirect()
The mutator will receive the value that is being set on the attribute, so your mutator method should be like this on you Product model
public function setTotalAttribute()
{
$this->attributes['total'] = $this->quantity * $this->price;
}

data is not submitting into db

I’m trying to signup user, initially it was working but now its not , when i enter data and click on signup then nothing happens, any solution to resolve this issue?
this is UsersController:
public function register(Request $request){
if($request->isMethod('post')){
$data = $request->all();
/*echo "<pre>"; print_r($data); die;*/
// Check if User already exists
$usersCount = User::where('email',$data['email'])->count();
if($usersCount>0){
return redirect()->back()->with('flash_message_error','Email already exists!');
}else{
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();
// Send Confirmation Email
$email = $data['email'];
$messageData = ['email'=>$data['email'],'name'=>$data['name'],'code'=>base64_encode($data['email'])];
Mail::send('emails.confirmation',$messageData,function($message) use($email){
$message->to($email)->subject('Confirm your E-com Account');
});
return redirect()->back()->with('flash_message_success','Please confirm your email to activate your account!');
if(Auth::attempt(['email'=>$data['email'],'password'=>$data['password']])){
Session::put('frontSession',$data['email']);
if(!empty(Session::get('session_id'))){
$session_id = Session::get('session_id');
DB::table('cart')->where('session_id',$session_id)->update(['user_email' => $data['email']]);
}
return redirect('/cart');
}
}
}
}
this is registeration form:
<form id="registerForm" name="registerForm" action="{{ url('/user-register') }}" method="POST">{{ csrf_field() }}
<input id="name" name="name" type="text" placeholder="Name"/>
<input id="email" name="email" type="email" placeholder="Email Address"/>
<input id="myPassword" name="password" type="password" placeholder="Password"/>
<button type="submit" class="btn btn-default">Signup</button>
</form>
and this is route:
Route::post('/user-register','UsersController#register');
The basic registration method in laravel with validation and auto login
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6',
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
Auth::login($user);
return redirect()->route('dashboard')
->with('success','Congratulation !!! You are registered successfully. Now you can login');
}
What is the error you will see in the blade template by adding this before form
#if($errors->all())
#foreach ($errors->all() as $error)
<div class="alert alert-danger">{{ $error }}</div>
#endforeach
#endif

Resources