User creation does not work on laravel 5.1 - laravel

actually i try to migrate some users from a excel file (.xlsx) to login in my aplication. But the code doesn't work.
The strange part is that the same code it's implemented for migrate payroll from a excel file (.xlsx) and this one work. I try many options, change some code, but it doesn't work.
Maybe I'm letting some error out and someone else can see it. I would appreciate the help.
Edit: I have a code in my routes.php that performs the migration, but from a table in the database, and this one works
My routes.php
Route::get("user_mig", function()
{
$contr = temporalestla\ContractUser::all();
foreach ($contr as $value)
{
$psw = \Hash::make($value->id_employee);
$user = new temporalestla\User
([
"full_name"=>$value->name_used,
"user" => $value->id_employee,
"password" => $psw,
"perfil" => 1
]);
$user->save();
}
return "Proceso finalizado";
});
My ImportController.php from users
public function cargar_datos_users(Request $request)
{
$file= $request->file('file');
$original_name=$file->getClientOriginalName();
$r1=Storage::disk('files')->put($original_name, \File::get($file) );
$route= storage_path('files') ."/". $original_name;
if($r1)
{
Excel::selectSheetsByIndex(0)->load($route, function($sheet)
{
$sheet->each(function($row)
{
$user = new User;
$user->full_name = $row->nombreempleado;
$user->user = $row->empleado;
$user->password = bcrypt($row->empleado);
$perfil = 1;
$user->perfil = $perfil;
$user->save();
});
});
return view("administrator.contracts.adminpayrolls")->with("msj","Usuarios Cargados Correctamente");
}
else
{
return view("administrator.contracts.adminpayrolls")->with("msj","Error al subir el archivo");
}
}
My app/User.php
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['full_name', 'user', 'password','perfil'];
protected $hidden = ['password', 'remember_token'];
}
The ajax script located in view.blade.php
<script type="text/javascript">
$(document).on("submit",".formarchivo",function(e)
{
e.preventDefault();
var formu=$(this);
var nombreform=$(this).attr("id");
if(nombreform=="f_cargar_datos_users" ){ var miurl="cargar_datos_users"; var divresul="notificacion_resul_fcdu"}
var formData = new FormData($("#"+nombreform+"")[0]);
$.ajax
({
url: miurl,
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function()
{
$("#"+divresul+"").html($("#cargador_empresa").html());
},
success: function(data)
{
alert("Usuarios cargados correctamente");
location.reload(true);
},
error: function(data)
{
alert("Error al subir usuarios. intente nuevamente");
location.reload(true);
}
});
});
</script>
#endsection
The plugin for migrate from excel is http://www.maatwebsite.nl/laravel-excel/docs
As I said, the same structure work on payroll migrate, but don't work on users migrate, any comments will be appreciate.

Related

laravel using jQuery Ajax | Ajax Cart

I'm Trying to Save The Product into The Database By Clicking On Add To Cart
But It's Not Adding I Also Use Ajax `
I Want To Add The Cart To DataBase And It's Not Adding.
This is The Error That I cant Add Any Product To The Cart Because Of It
message: "Call to undefined method App\User\Cart::where()", exception: "Error",…
enter image description here
Model Page.
class Cart extends Model
{
use HasFactory; I
protected $table = 'carts';
protected $fillable = [
'user_id',
'prod_id',
'prod_qty',
];
}
Controller page.
public function addToCart(Request $request)
{
$product_qty = $request->input('product_qty');
$product_id = $request->input ('product_id');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->pname." Already Added to cart"]);
}
else
{
$cartItem - new Cart();
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status' => $prod_check->pname." Added to cart"]);
}
}
}
else{
return response()->json(['status' => "Login to Continue"]);
}
}
javascript page.
This Is MY First Time To Use Ajax And Sure That Every Thing Is Correct I Want Know Why Its Not Add
$('.addToCartBtn').click(function (e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
success: function (response) {
alert(response.status);
}
});
// alert(product_id);
// alert(product_qty);
// // alert ("test ") ;
});
Route:
Route::middleware(['auth'])->group(function () {
Route::post('/add-to-cart', [App\Http\Controllers\User\indexController::class, 'addToCart' ]);});
So why this error occurs, how can I fix it?`
This look like an error in importation like App\Models\Cart not like this?
verify if you had added use App\Models\Cart;

Symfony 5 / Request Response : Get data with Ajax

when I try to get data in ajax, the returned object is empty
I send the id of the data I want to get in js :
function selectMessage(id) {
$.ajax({
url: '{{ path('back_translation_update') }}',
method: 'GET',
data: {id: id}
}).done(function (response) {
console.log(response)
})
}
$('.updateMessage').click(function (evt) {
evt.stopPropagation()
selectMessage($(this).data('id'))
})
in the controller I look for the data to return :
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request): Response
{
if ($request->isXMLHttpRequest()) {
$id = $request->get('id');
// dd($id);
$message = $this->translationService->getTranslationById($id);
// return new JsonResponse(['data' => $message]);
$response = new Response();
$response->setContent(json_encode([
'data' => $message,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
I use a service because with the repository I get an error: getById () must be an instance of Symfony\Component\HttpFoundation\Response
with :
$repositoryMessage = $this->em->getRepository(TranslationMessage::class);
$message = $repositoryMessage->findOneBy(['id' => $id]);
so the service will look in the database:
public function getTranslationById($translation_id)
{
$query = $this->em->createQueryBuilder()
->from(TranslationMessage::class,'message')
->select('message')
->where('message.id = ?1')
->setParameter(1, $translation_id);
$message = $query->getQuery()->getResult();
// dd($message);
return $message;
}
all the dd() give the expected values:
into getById(): the id of the row sought
into getTranslationById(): the sought object
but in the XHR, data contains an empty object: uh:
same with a new JsonResponse, commented here
what did I miss? help
Use Aurowire to get messageRepository object and use $this->json() to return JsonResponse
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request, TranslationMessageRepository $messageRepository): JsonResponse
{
$id = $request->query->get('id');
$message = $messageRepository->find($id);
if(!$message) { return new NotFoundHttpException(); }
return $this->json([
'success' => true,
'data' => $message
]);
}
Define success function instead of done function
function selectMessage(id) {
$.ajax({
url: "{{ path('back_translation_update') }}",
method: 'GET',
data: { id: id }
success: function(data) {
console.log(data)
}
})
}

The Ajax pagination to my account not run

I would like to create an Ajax pagination of my articles in my account, here is my code that I created but it does not work I do not know how to do.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
I would like to have the javascript code
$(document).ready(function () {
$(document).on('click','.pagination a',function(e){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var url = $(this).attr('href');
$.ajax({
url: url,
method: 'GET',
data: {},
dataType: 'json',
success: function (result) {
if (result.status == 'ok'){
$('#userListingGrid').html(result.listing);
}else{
alert("Error when get pagination");
}
}
});
return false;
})
});
I would have a check on your controller for an ajax request like so:
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
if(request()->ajax()){
return response()->json(['user' => $user, 'articles' => $user->articles()->orderByDesc('created_at')->paginate(4);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
Then you don't have to load your view every time and you can let your javascript functions take care of the DOM manipulating of the results. Not sure if that's what you are looking for. I know that you would probably need a {{$articles->links()}} at the end of your view to go through each page.

How to edit records of two tables at the same time in cakephp 3?

I need help: I do not know how to edit two tables of the database from the same form. I'm using cakephp3.
I'm trying to use ajax
Thanks for your help
Data to save in a different driver, there the script
This script is in a controller called carsController
**<script type="text/javascript">**
function editarCliente(a, b ){
var parametros = {
"clasificacionC" :a,
"descripcion": b,
};
$.ajax({
data: parametros,
url: '<?php echo router::url(array('controller'=>'Clientes','action'=>'editarcliente',$cliente->id));?>',
type: 'post',
dataType: 'json',
success: function (response) {
$("#nomCliente").val(response.uno+" "+response.dos);
$("#telCliente").val(response.tres);
$("#celCliente").val(response.cuatro);
}
});
}
**</script>**
This method is in a controller called clientesController.
public function editarcliente($id = null)
{
$cliente = $this->Clientes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$cliente->clasifi_cliente=$_POST("clasificacionC");
$cliente->descripcion=$_POST("descripcionC");
if ($this->Clientes->save($cliente)) {
$this->Flash->desactivar(__('Cliente desactivado'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The cliente could not be saved. Please, try again.'));
}
}
$this->set(compact('cliente'));
$this->set('_serialize', ['cliente']);
}

Symfony2: Save Record From Ajax Form Submission

I am totally lost. There's only so much documentation one can read before it all starts making zero sense.
I want to be able to save form data passed from outside of my Symfony application. I have already installed FOSRestBundle, JMSSerializerBundle, NelmioCorsBundle, etc.
First off, I have a FormType that looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('requestDate')
->add('deliverDate')
->add('returnDate')
->add('created')
->add('updated')
->add('contentChangedBy')
;
}
Then I have a REST controller containing the POST method which is supposed to store the new record:
class AvRequestController extends Controller
{
...
public function postAvrequestAction(Request $request){
$entity = new AvRequest();
$form = $this->createForm(new AvRequestType(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return new \Symfony\Component\HttpFoundation\JsonResponse($entity, Codes::HTTP_CREATED);
}
return new \Symfony\Component\HttpFoundation\JsonResponse($request, 400);
}
}
Here is the test with the mock ajax form data:
$('#postform').submit(function(event){
event.preventDefault();
console.log("submitted");
ajaxObject = {
url: $("#postform").attr("action"),
type: 'POST', // Can be GET, PUT, POST or DELETE only
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({"id":2, "title":"billabong", "requestDate":"2000-01-01 11:11:11", "deliverDate": "2000-01-01 11:11:11", "returnDate": "2000-01-01 11:11:11", "created": "2000-01-01 11:11:11", "updated": "2000-01-01 11:11:11", "content_changed_by":"cpuzzuol"})
};
// ... Add callbacks depending on requests
$.ajax(ajaxObject)
.done(function(data,status,xhr) {
console.log( two );
})
.fail(function(data,status,xhr) {
console.log( status );
})
.always(function(data,status,xhr) {
console.log( data );
});
console.log("END");
});
When I submit the form, the 400 Bad Request is tripped in my POST method. Worse, my $request bag is always empty:
{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}
If I do
$request->getContent()
I get my stringified data:
"{\u0022id\u0022:2,\u0022title\u0022:\u0022billabong\u0022,\u0022requestDate\u0022:\u00222000-01-01 11:11:11\u0022,\u0022deliverDate\u0022:\u00222000-01-01 11:11:11\u0022,\u0022returnDate\u0022:\u00222000-01-01 11:11:11\u0022,\u0022created\u0022:\u00222000-01-01 11:11:11\u0022,\u0022updated\u0022:\u00222000-01-01 11:11:11\u0022,\u0022content_changed_by\u0022:\u0022cpuzzuol\u0022}"
I've read that this might have something to do with FOSRestBundle's "body listener" but I've already enabled that:
body_listener: true
UPDATE
body_listener doesn't seem to play a role at all. As the answer below states, you have to create a form with a blank name since the form you are submitting from outside of the system isn't going to have the name it would normally have if it were made inside of Symfony. Also, make sure to turn off CSRF if you don't have that set up at first.
Form isValid checks also for CSRF token validation. You can turn off csrf token validation in AvRequestType.
//...
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\AvRequest',
'csrf_protection' => false
));
}
//...
Also, I suggest your form has name. isValid also checks for your form name.
// form without name
public function getName()
{
return '';
}
Or
$form = $this->get('form.factory')->createNamed('', new AvRequestType(), $avRequest);
If you want to create entity, you should send data without id(from JS).
I have used "JMS serializer" to serialize my entity to json.
//Controller
public function postAvRequestAction(Request $request)
{
$avRequest = new AvRequest();
$form = $this->createForm(new AvRequestType(), $avRequest);
$form->handleRequest($request);
$form = $this->get('form.factory')->createNamed('', new AvRequestType(), $avRequest);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($avRequest);
$em->flush();
$serializer = $this->get('serializer');
$serialized = $serializer->serialize($avRequest, 'json');
return new Response($serialized);
}
return new JsonResponse(array(
'errors' => $this->getFormErrors($form)
));
}
protected function getFormErrors(Form $form)
{
$errors = array();
foreach ($form->getErrors() as $error) {
$errors['global'][] = $error->getMessage();
}
foreach ($form as $field) {
if (!$field->isValid()) {
foreach ($field->getErrors() as $error) {
$errors['fields'][$field->getName()] = $error->getMessage();
}
}
}
return $errors;
}

Resources