Laravel array of object update failing for unique email - laravel-6

I am using Laravel 6.I have an API that sends an array of staff, some are existing objects that need to be updated and some are new objects that need to be created. The creation part works but update fails due to "DUPLICATE ENTRY for UNIQUE EMAIL".I am using a function in controller
class AdminController extends Controller
{
public function userTransfer()
{
$caremanagementUserData = Admin::on('validated')->get();
$caremanagementUserData->each(function($userData)
{
if(User::where('email', '=', $userData['email'])->exists()) {
User::on('mysql')->where('id', '=',$userData['id'])->update([
'username' => $userData['username'],
'email' => $userData['email'],
'password' => $userData['password']
]);
} else {
User::on('mysql')->insert([
'username' => $userData['username'],
'email' => $userData['email'],
'password' => $userData['password']
]);
}
});
}
}
Help me about how to send email in the update array to solve the unique email error.

I found a way to get around the problem. Because email is unique and if email existence is being checked by
if(User::where('email', '=', $userData['email'])->exists())
{}
email update should be omitted from array of object, and if a new email is send it will be inserted as new data. It works for me !

Related

How can is possible to attach different roles to users in the exact moment of registration?

before starting I premise and humbly apologize: I am a neophyte regarding the use of Laravel framework. I Searched eveywhere even the documentation but without results.
My question is if it is possible to assign a role at registration time using the Laratrust library. We want for example that the first 4/5 users who register are administrators, from the fifth onwards are normal users with restricted permissions.
This is the code regarding the Controller for registration.
RegisterController.php
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
if(Auth::id() < 4 ){
$user->attachRole('administrator');
}
else{
$user->attachRole('user');
}
return $user;
}
This is the method that aims to register the user from the form, for some reason when I go to take the current id of the user, the condition in the if statement is bypassed, in fact in the database in the table roles i always have users that are administrators. I am thinking that maybe the real problem is Auth Class beacuse if i understood correctly this class is used when a user is already logged.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$checklatestid = User::latest()->pluck('id')->first();
if($checklatestid < 4 ){
$user->attachRole('administrator');
//Ruolo amministratore impianto scii
}
else{
$user->attachRole('user');
//Ruolo cliente impianto scii
}
return $user;
}
If understand you correctly

How to create a trigger to populate a table in database based on saved data in another table from laravel controller

I am creating an API with Laravel where I am trying to populate a table in a database based on saved data in another table in the database. So after table 1 data is saved, it should trigger for table 2 data to be also saved.
Here is the code for Controller of table 1
public function create(Request $request)
{
//
$this->validate($request, [
'name' => 'required|unique:users',
'code' => 'required'
]);
Auth::user();
$user = new User();
$user->inputed_code = $request->inputed_code;
$user->code = $request->code;
$user->save();
return response([
'success' => true,
'message' => 'Data has been saved!!',
'data' => $user,
], Response::HTTP_OK);
}
Here is the Controller for table 2 which I want to populate based on result from table 1 through a trigger effect.
public function reward(Request $request)
{
//
$reward = new Reward();
$reward->user_id = DB::table('users')->get(id)
$reward->points = $request->referral_reward;
$reward->save();
$user = $request->only('user_id');
$reward = Reward::where('user_id', '=', $user)->update([
'referral_reward' => 5
]);
return response()->json([
'success' => true,
'message' => 'You have been awarded 5 points',
'data' => $reward,
], Response::HTTP_CREATED);
}
Here are the API routes
Route::post('applycode', 'UserController#create');
Route::post('reward', 'RewardController#reward');
Please what am I doing wrong and is there is better way to approach this is give the same results.
Thank you
I understand that based on a saved User model you want to save something in your rewards table.
You could use Eloquent events. Register an event in your User model like this:
class User extends Model {
// ... other stuff
protected $dispatchesEvents = [
'saved' => UserSaved::class,
];
}
Then you need to create your events file by running php artisan make:event UserSaved, which creates a file app/Events/UserSaved.php. In this files __construct method you receive the affected model as parameter.
public function __construct(User $user)
{
// ... do sth
}
Then you need event listeners, see the docs, to consume the event
After defining and mapping your Eloquent events, you may use event listeners to handle the events.
Then inside the listener you can do all the logic you want to apply to your Rewards model.

API post request not reaching the application

i'm new to laravel and i'm facing a painful problem.
I'm using Crinsane/LaravelShoppingcart in my ecommerce api and i'm trying to send a post request with axios in vuejs that adds a product to the cart by sending the product id and the quantity. The problem is the id and quantity are not reaching the application although i'm pretty sure i specified the correct route link in axios and i'm getting "No query results for model [App\Product]." which i assume means that the controller function that handles the request is working but the id is not being sent/transformed to the resource collection. I don't know if the problem is with the package i'm using or the code or something else.
this is axios request
addCart(item) {
axios
.post('/api/cart/add', item)
.then(response => (response.data.data))
.catch(error => console.log(error.response.data))
this is the route :
Route::post('cart/add', [
'uses' => 'ShoppingController#store',
'as' => 'cart.add'
]);
this is the cart collection
public function toArray($request)
{
return [
'id' => $this->id,
'qty' => $this->qty
];
}
this is the controller
public function store(){
$pdt = Product::findOrFail(request()->id);
$cart = Cart::add([
'id' => $pdt->id,
'name' => $pdt->name,
'qty' => request()->qty,
'price' => $pdt->price
]);
and this is the product model
class Product extends Model
{
protected $fillable = [
'name', 'description', 'image', 'category', 'quantity', 'price', 'sold','remaining','rating', 'bestSelling', 'featured'
];
}
Thank you in advance
The problem seems to be in your controller.
From the docs:
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method.
Try this:
public function store(Request, $request){
// Make sure the 'id' exists in the request
if ($request->get('id')) {
$pdt = Product::find($request->get('id'));
if ($request->get('qty')) {
$qty = $request->get('qty')
}
$cart = Cart::add([
'id' => $pdt->id,
'name' => $pdt->name,
'qty' => $qty,
'price' => $pdt->price
]);
}
Then, at the top of your controller, add:
use Illuminate\Http\Request;
So i found that it needed a json object to work and i had to put this code at the end of the store method :
return response()->json(['cart' => $cart], 201);

Laravel 5.6 - creation user not working

my application used to working well with registration user but now it dont.
here a portion of my model User
protected $fillable = [
'prenom', 'nom', 'email','photo_path','password',
];
here my validation function :
protected function validator(array $data)
{
return Validator::make($data, [
'prenom' => 'required|string|max:255',
'nom' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'photo_path' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
'password' => 'required|string|min:6|confirmed',
]);
}
here my create function :
protected function create(array $data)
{
dd($data);
$photoInput = request('photo_path');
$userPhotoPath='users';
$storagePhotoPath = Storage::disk('images')->put($userPhotoPath, $photoInput);
return User::create([
'prenom' => $data['prenom'],
'nom' => $data['nom'],
'email' => $data['email'],
'photo_path' => $storagePhotoPath,
'password' => Hash::make($data['password']),
]);
}
- POST request working ( return 302 ) but return back with input value
- Auth Route are declared in web.php
- Validation working well
but the php interpretor didnt get inside create function...
i just see in debugbar that information :
The given data was invalid./home/e7250/Laravel/ManageMyWorkLife/vendor/laravel/framework/src/Illuminate/Validation/Validator.php#306Illuminate\Validation\ValidationException
public function validate()
{
if ($this->fails()) {
throw new ValidationException($this);
}
$data = collect($this->getData())
but my validation working because i have error message near my InputTexte.
so i dont understand that error message ...
Do you have any clue ?
Well, you need to remove the dd(); function before you run something. Other wise it will end the execution of all other operations.
Check if your User Model has a constructor, if so remove it and check if the problem still accours. This fixed it for me.

ZF2 / doctrine ORM authentication different Entity

in my application (ZF2 / ORM) i have 3 Entities (with Single Table inheritance)
User
Owner extends User
Agent extends User
i want to make one single Authentication (Login) for the 3 Entity using
doctrine.authenticationservice.orm_default
module.config.php
//other doctrine config
'authentication' => array(
'orm_default' => array(
'object_manager' => 'Doctrine\ORM\EntityManager',
'identity_class' => 'Application\Entity\User',
'identity_property' => 'email',
'credential_property' => 'password',
'credential_callable' => function(User $user, $passwordGiven) {
return $user->getPassword() == md5($passwordGiven);
},
),
),
and the process of login
//LoginController.php
// ..data validation
$this->authService = $this->getServiceLocator()->get('doctrine.authenticationservice.orm_default');
$AuthAdapter = $this->authService->getAdapter();
$AuthAdapter->setIdentity($this->request->getPost('email'));
$AuthAdapter->setCredential(md5($this->request->getPost('password')));
$result = $this->authService->authenticate();
if($result->isValid()){
$identity = $result->getIdentity();
//continue
}
how can i do this process without caring about object type,
when i try to login with email of an Agent, i get this error
Catchable fatal error: Argument 1 passed to Application\Module::{closure}() must be an instance of User, instance of Application\Entity\Owner given
The error you mention is due to the type hint on:
function(User $user) {
Which leads me to believe that you have a missing namespace declaration in your config file; in which case you can either add it or use the FQCN.
function(\Application\Entity\User $user) {
Nevertheless, I don't think it's actually the problem. You can only define one 'identity_class' with doctrine authentication (which the adapter will use to load the entity from the entity manager). If you have multiple entity classes there is no way to have each of these tested with one adapter.
However, the configuration is really just creating a new authentication adapter, specifically DoctrineModule\Authentication\Adapter\ObjectRepository. One solution would be to create multiple ObjectRepository adapters, each with the correct configuration for the different entities and then loop through each of them while calling authenticate() on the Zend\Authentication\AuthenticationService.
For example :
public function methodUsedToAutheticate($username, $password)
{
// Assume we have an array of configured adapters in an array
foreach($adapters as $adapter) {
$adapter->setIdentity($username);
$adapter->setCredential($password);
// Authenticate using the new adapter
$result = $authService->authenticate($adapter);
if ($result->isValid()) {
// auth success
break;
}
}
return $result; // auth failed
}
As previously mentioned is the doctrine config will not allow for more than one adapter, so you would need to create them manually and remove your current configuration.
Another example
public function getServiceConfig()
{
return [
'factories' => [
'MyServiceThatDoesTheAuthetication' => function($sm) {
$service = new MyServiceThatDoesTheAuthetication();
// Assume some kind of api to add multiple adapters
$service->addAuthAdapter($sm->get('AuthAdapterUser'));
$service->addAuthAdapter($sm->get('AuthAdapterOwner'));
$service->addAuthAdapter($sm->get('AuthAdapterAgent'));
return $service;
},
'AuthAdapterAgent' => function($sm) {
return new DoctrineModule\Authentication\Adapter\ObjectRepository(array(
'object_manager' => $sm->get('ObjectManager'),
'identity_class' => 'Application\Entity\Agent',
'identity_property' => 'email',
'credential_property' => 'password'
));
},
'AuthAdapterOwner' => function($sm) {
return new DoctrineModule\Authentication\Adapter\ObjectRepository(array(
'object_manager' => $sm->get('ObjectManager'),
'identity_class' => 'Application\Entity\Owner',
'identity_property' => 'email',
'credential_property' => 'password'
));
},
// etc...
],
];
}
Hopefully this gives you some ideas as to what is required.
Lastly, if you would consider other modules, ZfcUser already has a 'chainable adapter' which actually does the above (but uses the event manager) so It might be worth taking a look at even if you don't use it.