Email Vaildation Magento 2.2 - magento2.2

jQuery(function() {
var emailAddress = jQuery('#email_address');
emailAddress.on("change", function () {
var mail=emailAddress.val();
jQuery.ajax({
type: "POST",
url: "/customer/email/",
dataType: "json",
data: {email: mail},
success: function (exist) {
if (exist == 1) {
alert("exist");
} else if (exist == 0) {
alert("exist");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error " + jqXHR.status + " " + jqXHR.statusText);
}
});
});
});
Controller email.php
public function execute()
{
$customerEmail=$this->getRequest()->getParam('email');
$objectManager=\Magento\Framework\App\ObjectManager::getInstance();
$CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
$CustomerModel->setWebsiteId(1);
$CustomerModel->loadByEmail($customerEmail);
$userId = $CustomerModel->getId();
if ($userId) {
return 1;
} else {
return 0;
}
I want to check email before clicking create an account button using Ajax, i am not getting to do that, please help me out to solve this issue, thanks in advance.

It seems like you are trying to validate email address as customer enter his email address. For this you just need minor change in the email address field.
<input type="email" name="email" id="email_address" autocomplete="off" value="<?php echo $block->escapeHtml($block->getFormData()->getEmail()) ?>" title="<?php /* #escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true, 'remote':'<?php echo $this->getUrl('customcustomer/index/uniqueemail', ['_secure' => true]); ?>'}"/>
Create a controller and add you logic in execute method.
<?php
namespace Gaurav\CustomCustomer\Controller\Index;
use Magento\Framework\App\Action\Action;
class Uniqueemail extends Action
{
/**
* #var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
/**
* #var \Magento\Customer\Model\Customer
*/
protected $_customerModel;
/**
* #param \Magento\Framework\App\Action\Context $context
* #param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Customer\Model\Customer $customerModel
) {
$this->resultJsonFactory = $resultJsonFactory;
$this->_customerModel = $customerModel;
parent::__construct($context);
}
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
$email = $this->getRequest()->getParam('email');
$customerData = $this->_customerModel->getCollection()
->addFieldToFilter('email', $email);
if(!count($customerData)) {
$resultJson->setData('true');
} else {
$resultJson->setData('That email is already taken, try another one');
}
return $resultJson;
}
}
I hope this will be helpful to you.

Related

Pusher returns no data with laravel 8 event

I'm using laravel 8, and I'm having a hard time getting the data from the event using pusher. I'm want to broadcast the event, i want to receive the data when the data is successfully inserted in the database. hope someone can help me with this. here are my codes
config/app.php
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class
Events\Chat.php
class Chat implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('chat');
}
public function broadcastAs()
{
return 'get-chat';
}
}
chat.blade.php
var pusher = new Pusher('dec355f1ff67f51f5784', {
cluster: 'ap1',
forceTLS: true
});
Pusher.logToConsole = true;
$('.chat-send').click(function(){
var msg = $('.chat-msg').val();
$.ajax({
url: add_url,
type: 'POST',
data: {'msg' : msg},
dataType: 'json',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function(data) {
if (data.msg == 'success') {
var channel = pusher.subscribe('chat');
channel.bind('pusher:subscription_succeeded', function(data) {
//alert('successfully subscribed!');
console.log(data);
});
channel.bind('get-chat', function(data) {
//console.log(JSON.stringify(data));
alert(data);
});
}
},
error : function(request, status, error) {
//swal("Oops!", "Seems like there is an error. Please try again", "error");
}
});
});
MessageController
public function create(Request $request, Messages $messages)
{
$request->merge([
'teacher_id' => 2,
'student_id' => 1,
'message' => 'test msg'
]);
$data = $messages::create($request->all());
if ($data->exists) {
$msg = 'success';
$cars = ['hey', 'yow'];
broadcast(new Chat($cars));
}
return json_encode(['msg'=>$msg]);
}
This is what I get in the pusher.log
Pusher : : ["Event sent",{"event":"pusher:subscribe","data":{"auth":"","channel":"chat"}}]
Pusher : : ["Event recd",{"event":"pusher_internal:subscription_succeeded","channel":"chat","data":{}}]

Laravel/Vue form Validation

I'm having a problem with validation when it comes to Laravel and Vue
My controller has logic like this.
$this->validate($request, [
"name" => ["required", "min:3"]
]);
Vue only recognizes one of the two validations, however. For example, if the text field isn't at least 3 characters long Vue will still allow all to go through, claiming that the name field is still required.
The only error that displays on the front end is the "required" rule, there's nothing there for "min:3".
Any advice? Or if anyone can lead me to a good source with VueJS/Laravel validation that would be awesome too,
thanks in advance.
Another odd thing is that though the name field is required even if it is fulled in, Laravel still returns that error in the console 422.
VueJS Component
<template>
<!-- Third paramater in v-bind="" class will be used in either -->
<div>
<form v-on:submit.prevent>
<div class="section">
<div class="field level">
<p class="control has-text-centered">
<input
id="name"
name="name"
v-model="item.name"
class="input is-rounded is-large"
type="text"
placeholder="Enter Todo.."
v-bind:class="[
item.name ? 'is-success' : 'is-normal',
'plus'
]"
/>
</p>
</div>
<div class="alert alert-danger" v-if="errors && errors.name">
{{ errors.name[0] }}
</div>
<button
#click="addItem()"
class="button is-primary is-fullwidth"
>
<font-awesome-icon
icon="plus-square"
class="color is-primary"
/>
</button>
</div>
</form>
</div>
</template>
<script>
export default {
data: function() {
return {
item: {
name: ""
},
errors: {}
};
},
methods: {
addItem() {
// if (this.item.name === "") {
// return;
// }
axios
.post("api/item/store", {
item: this.item
})
.then(response => {
if (response.status == 201) {
this.item.name = "";
this.$emit("reloadlist");
this.errors = {};
}
})
.catch(error => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
console.log(error);
});
}
}
};
</script>
<style scoped>
p {
margin: auto;
}
</style>
PHP Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Item;
use Illuminate\Support\Carbon;
class ItemsController extends Controller
{
/**
* Display a listing of the item resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Item::orderBy("created_at", "DESC")->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
"name" => ["required", "min:3"]
]);
$newItem = new Item;
$newItem->name = $request->item["name"];
$newItem->save();
dd("Hello, World");
return $newItem;
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$existingItem = Item::find($id);
if ($existingItem) {
$existingItem->completed = $request->item["completed"] ? true : false;
$existingItem->completed_at = $request->item["completed"] ? Carbon::now() : null;
$existingItem->save();
return $existingItem;
}
return "Item not found.";
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$existingItem = Item::find($id);
if ($existingItem) {
$existingItem->delete();
return "Item '{$existingItem->name}' deleted successfully.";
}
return "Item not found.";
}
}
Item is already an object so you dont need it to put in an object variable and the name it item.
Change your axios request to:
methods: {
addItem() {
// if (this.item.name === "") {
// return;
// }
axios
.post("api/item/store", this.item)
.then(response => {
if (response.status == 201) {
this.item.name = "";
this.$emit("reloadlist");
this.errors = {};
}
})
.catch(error => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
console.log(error);
});
}
}
I think this will solve your problem.

"Object of class App\User could not be converted to int" error in Laravel

I'm trying to save new user with Ajax request in Laravel and i'm getting the following error,
Object of class App\User could not be converted to int
I must add the the user is saved, so i'm not sure from where this error comes.
Here is the UserController:
public function save_user(Request $request)
{
try {
if (request()->ajax()) {
$lastUserId = User::where('user_id', '>', 0)->orderBy('user_id', 'desc')->get('user_id')->first()->toArray();
$user = new User;
$data = Input::all();
$user->user_id = intval($lastUserId['user_id'] + 1);
$user->user_type = $data['user_type'];
$user->email = $data['email'];
$user->password = 'e10adc3949ba59abbe56e057f20f883e';
$user->first_name = $data['first_name'];
$user->last_name = $data['last_name'];
$user->save();
if ($user > 0) {
return response()->json('Success');
}
return response()->json(['status' => 200, 'message' => 'save success']);
}
} catch (\Exception $e) {
echo $e->getMessage();
}
Here is the Ajax request:
$('#saveUser').on('click', function (e) {
e.preventDefault();
var $inputs = $('#new-user-form :input');
var values = {};
$inputs.each(function () {
if (this.name != '_token' && this.name.length > 0) {
values[this.name] = $(this).val();
}
});
$.ajax({
url: '/api/save_user',
type: "post",
data: values,
dataType: 'JSON',
success: function (data) {
/// location.reload();
}
});
})
Here is the User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Detail;
class User extends Authenticatable
{
public function users(){
return $this->hasMany('\App\User'); //Product Model Name
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
I've tried to convert all the input values to their type - like in the DB but it didn't worked
In your condition, you are trying to see if a collection of user is > 0, and because of that, you're getting the error above, since Laravel is trying to parse the collection of user to int datatype, to make it countable. Refactor your condition to this:
if (count($user) > 0) {
return response()->json('Success');
}
or another way:
if ($user) {
return response()->json('Success');
}
Try to change this in your controller
if ($user > 0) {
return response()->json('Success');
}
To this
if ($user) {
return response()->json('Success');
}

Laravel paginate

The model works well. The controller works well. The only place I'm having an error is in the view.
class Course extends Model
{
use SoftDeletes, FilterByUser;
protected $fillable = ['title', 'description', 'course_image', 'start_date', 'active', 'mandatory', 'created_by_id'];
protected $hidden = [];
public static $searchable = [
'title',
'description',
];
public static function boot()
{
parent::boot();
Course::observe(new \App\Observers\UserActionsObserver);
}
/**
* Set attribute to date format
* #param $input
*/
public function setStartDateAttribute($input)
{
if ($input != null && $input != '') {
$this->attributes['start_date'] = Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
} else {
$this->attributes['start_date'] = null;
}
}
/**
* Get attribute from date format
* #param $input
*
* #return string
*/
public function getStartDateAttribute($input)
{
$zeroDate = str_replace(['Y', 'm', 'd'], ['0000', '00', '00'], config('app.date_format'));
if ($input != $zeroDate && $input != null) {
return Carbon::createFromFormat('Y-m-d', $input)->format(config('app.date_format'));
} else {
return '';
}
}
/**
* Set to null if empty
* #param $input
*/
public function setCreatedByIdAttribute($input)
{
$this->attributes['created_by_id'] = $input ? $input : null;
}
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
public function trainers()
{
return $this->belongsToMany(User::class, 'course_user');
}
public function lessons()
{
return $this->hasMany('\App\Lesson');
}
}
I seem to have an issue with pagination. Here is the code I have for the controller and that works well.
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Here is what I have for the view:
{{$course->links()}}
this is where I get an error Call to undefined method App\Course::link()
Does anyone know what I'm doing wrong?
The Controller Code :
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Here is for the view:
#foreach($course as $row)
//Whatever you wanted to display will be written here
#endforeach
{!! $course->render() !!}
OR
#foreach($course as $row)
//Whatever you wanted to display will be written here
#endforeach
{{$course->links()}
The Controller code is fine.
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Now let's take a look at view.
#foreach($course as $row)
//Whatever action you wanted to do will be written here
#endforeach
{{$course->links()}} //The name should be differ than the name we used inside the foreach loop.

Symfony 3 Ajax Login Invalid CSRF Token

I am trying to login with my modal and send an Ajax request for the authentication but i get always this error from the onAuthenticationFailure function:
Invalid CSRF token
Here is my code:
security.yml
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
default:
anonymous: ~
pattern: ^/
form_login:
provider: picshare_provider
check_path: /login
success_handler: acme.security.authentication_handler
failure_handler: acme.security.authentication_handler
csrf_token_generator: security.csrf.token_manager
csrf_parameter: _csrf_token
AuthenticationHandler.php
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface , AuthenticationFailureHandlerInterface
{
private $router;
private $session;
private $csrfTokenManager;
/**
* AuthenticationHandler constructor.
* #param RouterInterface $router
* #param Session $session
*/
public function __construct(RouterInterface $router, Session $session, CsrfTokenManagerInterface $csrfTokenManager)
{
$this->router = $router;
$this->session = $session;
$this->csrfTokenManager = $csrfTokenManager;
}
/**
* #param Request $request
* #param TokenInterface $token
* #return RedirectResponse|Response
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
if ($request->isXmlHttpRequest()) {
$json = array(
'has_error' => false,
'username' => $token->getUser()->getUsername()
);
$response = new Response(json_encode($json));
$response->headers->set('Content-Type', 'application/json');
return $response;
} else {
$url = $this->router->generate('home');
return new RedirectResponse($url);
}
}
/**
* #param Request $request
* #param AuthenticationException $exception
* #return Response
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if ( $request->isXmlHttpRequest() ) {
$array = array( 'success' => false, 'message' => $exception->getMessage() ); // data to return via JSON
$response = new Response( json_encode( $array ) );
$response->headers->set( 'Content-Type', 'application/json' );
return $response;
}
else {
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
return new RedirectResponse($this->router->generate('login'));
}
}
}
JavaScript.js
login_submit.onclick = function () {
axios.post('/login',
{
_username: document.getElementById('login-email').value = 'admin',
_password: document.getElementById('login-password').value = 'root',
_csrf_token: document.getElementById('login-csrf').value
},
config).then(function (response) {
console.log(response)
})
};
Controller:
/**
* #Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
$csrfToken = $this->has('security.csrf.token_manager')
? $this->get('security.csrf.token_manager')->getToken('authenticate')->getValue()
: null;
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
$array = [
'error' => $error,
'csrf_token' => $csrfToken,
];
$response = new Response(json_encode($array));
return $response;
}
twig
<form class="cd-form">
<p class="fields">
<label class="email" for=login-email">Benutzername</label>
<input id="login-email" name="_username" >
<i class="fa fa-envelope-o" aria-hidden="true"></i>
</p>
<p class="fields">
<input id="login-password" name="_password" placeholder="Passwort">
<i class="fa fa-key" aria-hidden="true"></i>
</p>
<p class="fields-submit">
<input class="full-width" id="modal-login-button" value="Anmelden">
</p>
<input type="hidden" name="_csrf_token" id="login-csrf"
value="{{ csrf_token('authenticate') }}"
>
</form>
What am I missing?

Resources