Laravel 5 form request - request

When I handle a CREATE post form, i'll do :
public function handlecreer(Requests\CreerUtilisateurRequest $request)
{
// handle create form
// all fields in one line... YEAH !!!
$user = new User($request->except('password','role'));
$user->password = bcrypt(Request::input('password'));
$user->save();
....}
But if I have an UPDATE post form I'll do :
public function handleUpdate(Requests\UpdateUtilisateurRequest $request)
{
// handle update form
$user = User::findOrFail(Request::input('id'));// find
// one line by field... BOH !!!
$user->name = Request::input('name');
$user->email = Request::input('email');
$user->password = bcrypt(Request::input('password'));
$user->telephone= Request::input('telephone');
$user->fonction = Request::input('fonction');
$user->divers = Request::input('divers');
$user->save();
....}
Is there a simplest way of processing the update post form ?
Thanks,
Paguemaou

All mass assignable attributes (the one in $fillable) can be set using fill():
$user = User::findOrFail(Request::input('id'));
$user->fill($request->except('password', 'role'));
$user->password = bcrypt(Request::input('password'));
$user->save();

Related

save mathod in database cause Array to string conversion error in laravel

when I execute custom command with
php artisan query:all
every thing is good except error shown in console the error is
Array to string conversion
and the data is stored to database I did not understand the cause of this error and it's hidden when hide save to database method
the code of my service which the problem cause inside it is
<?php
namespace App\Services;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Models\weatherStatus;
use Illuminate\Support\Collection;
class ApixuService
{
public function query(string $apiKey, Collection $cities): Collection
{
$result = collect();
$guzzleClient = new Client([ //create quzzle Client
'base_uri' => 'http://api.weatherstack.com'
]);
foreach ($cities as $city) {
$response = $guzzleClient->get('current', [
'query' => [
'access_key' => $apiKey,
'query' => $city->name,
]
]);
$response = json_decode($response->getBody()->getContents(), true); //create json from $response
$status = new weatherStatus(); //create weatherStatus object
//adding prameters
$status->city()->associate($city);
$status->temp_celsius = $response['current']['temperature'];
$status->status = $response['current']['weather_descriptions'];
$status->last_update = Carbon::createFromTimestamp($response['location']['localtime_epoch']);
$status->provider = 'weatherstack.com';
//save prameters
$status->save();
$result->push($status);
}
return $result;
}
}
So you can find some clarity in what you are trying to save, do the following:
$response = json_decode($response->getBody()->getContents(), true);
dd($response);
dd() will dump all the data from the $response and exist the script.
One of the values you are trying to save is an array. The field you are trying to save accepts a string and not array.

Persist array store in session symfony

It's been several days since I've been blocking to persist items from an order into session to database.
I stock articles in session in an array and I do not know how to persist the array. I try to convert the array into an object, I can not. This is my service:
public function addArticle($id)
{
$sessionCart = $this->session;
$article = $this->doctrine->getRepository('AppBundle:Article')->find($id);
$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);
// use later for delivery
$sessionCart->get('commande');
return $sessionCart;
}
public function panier()
{
$articles = $this->session->get('cart');
return $articles;
}
public function delivery(Request $request)
{
$commande = new Commande();
$articles = $this->session->get('cart');
$form = $this->form->create(CommandeType::class, $commande);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
{
$data = $form->getData();
$this->session->set('commande', $data);
$response = new RedirectResponse('payment');
$response->send();
}
return [$form, $articles];
}
public function payment(Request $request)
{
$articles = $this->session->get('cart');
$commande = $this->session->get('commande');
if ($request->isMethod('POST')) {
$em = $this->doctrine;
$em->persist($articles);
$em->persist($commande);
$em->flush();
}
return[$articles, $commande];
}
Error : "EntityManager#persist() expects parameter 1 to be an entity object, array given."
The order is persisted but not the items.
Thanks
I can't understand these two lines
$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);
$cart is an array and should be an entity isn't it ?
The persist is waiting for an entity,
maybe you can persist in a foreach loop:
foreach($articles as $article){
$em->persist($article);
}
or use a doctrineCollection instead of an array

CakePHP 3 : display data from other model and pass parameter in url from action

I'm working on a project using CakePHP 3.x.
I have UserAddress, ServiceRequests, Service models.
There is a button on service/view/$id which when clicked will ask user to select address from service-requests/serviceArea which has a list of addresses added by user. service-requests/serviceArea view will contain a select button which when clicked will call add action in ServiceRequests controller with passing two parameters serviceId and userAddressId
This is the serviceArea function created by me.
public function serviceArea($id = null)
{
public $uses = array('UserAddress');
$service = $id;
$query = $userAddresses->find('all')
->where(['UserAddresses.user_id =' => $this->Auth->user('id')]);
$this->set(compact('userAddresses'));
$this->set('_serialize', ['userAddresses']);
}
How to display the address and also pass the $service parameter to the serviceArea view.
I am new to CakePHP, so if you think question is incomplete any edit to it will be appreciated instead of down-voting.
Thank You.
Edit 2
Thank for your answer #jazzcat
After changing my code according to yours and visiting http://domain.com/service-requests/service-area/$id. It is showing error as
Record not found in table "service_requests"
and pointing to the ServiceRequestsController on line no 33
The ServiceRequestController as containing line no 33 is
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* ServiceRequests Controller
*
* #property \App\Model\Table\ServiceRequestsTable $ServiceRequests
*/
class ServiceRequestsController extends AppController
{
/**
* isAuthorized method
*
*/
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// The add and index actions are always allowed.
if(in_array($action, ['index', 'add', 'serviceRequests'])) {
return true;
}
// All other actions require an id.
if (empty($this->request->params['pass'][0])) {
return false;
}
// Check that the service request belongs to the current user.
$id = $this->request->params['pass'][0];
$serviceRequest = $this->ServiceRequests->get($id); // line : 33
if($serviceRequest->user_id == $user['id']) {
return true;
}
return parent::isAuthorized($user);
}
/* Other actions */
}
?>
This worked for me.
Just added the serviceArea action name in the isAuthorized method
if(in_array($action, ['index', 'add', 'serviceArea'])) {
return true;
}
and it's working fine as expected.
There is alot wrong with your code. Please read the docs
Is the table named user_addresses or user_address ?
You seem to mix the both.
The following would be the correct way to do it assuming your table is named user_addresses
public function serviceArea($id = null)
{
$this->loadModel('UserAddresses');
$userAddresses = $this->UserAddresses->find('all')
->where(['UserAddresses.user_id =' => $this->Auth->user('id')]);
// If you want to filter on the serviceArea ID aswell
if($id)
$userAddresses->andWhere(['id' => $id]);
// Setting SerivceArea ID to compact makes it available in view.
$serviceAreaId = $id;
$this->set(compact('userAddresses', 'serviceAreaId'));
$this->set('_serialize', ['userAddresses']);
}
This snippet:
$id = $this->request->params['pass'][0];
$serviceRequest = $this->ServiceRequests->get($id); // line : 33
Just checks if the first parameter passed to the method exists in ServiceRequests.
(That parameter could be anything, you have to keep that in mind when creating all your methods in that controller, that is to say the least.. bad)
I'm assuming that the service_requests table is associated with the users table and an user_id column exists in the service_requests table.
If that is the case this should work:
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// The add and index actions are always allowed.
if(in_array($action, ['index', 'add'])) {
return true;
}
// Is not authorized if an argument is not passed to the method.
// Don't know why you'd want this , but sure.
if (empty($this->request->params['pass'][0])) {
return false;
}
// Check that the service request belongs to the current user.
$user_id = $this->Auth->user('id');
$serviceRequest = $this->ServiceRequests->find()->where(['ServiceRequests.user_id' => $user_id])->first();
if(!empty($serviceRequest)) {
return true;
}
return parent::isAuthorized($user);
}

CakePHP 2.5 Datasource, create and return response

I have a specific task to connect CakePHP web application to a remote restful server . I create a datasource, read method works great, but the api after save data return an array of processed data.
Looking for a way to return the data array and use in controller.
My Controller code
public function admin_generate()
{
$data = $this->request->data;
$data['path'] = 'special/generate';
$this->Tool->create();
if($this->Tool->save($data)){
// handle response ????
}
$this->set('data',$data);
$this->set('_serialize','data');
}
In datasource file
public function create(Model $model, $fields = null, $values = null)
{
$data = array_combine($fields, $values);
$api = $this->config['api_path'].$data['path'].'?auth_key='.$this->config['auth_key'];
$json = $this->Http->post($api, $data);
$response = json_decode($json, true);
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
return $response; // ??????
}
Can someone show me the correct way to use the api response data in the controller?
I found a solution, a few minutes after a post question. This can help one of you.
datasource
....
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
// SOLUTION
$model -> code = $response['code'];
$model -> key = $response['key'];
$model -> code_id = $response['code_id'];
return true;
.....
in controller
.....
if($this->Tool->save($data)){
unset($data['path']);
$data['code'] = $this->Tool->code;
$data['key'] = $this->Tool->key;
$data['code_id'] = $this->Tool->code_id;
}
.....

CakePHP 2.4 Forgotten Password

I have just started using CakePHP and love using it! I have created a login system and registration system, however am really struggling with the "forgotten password" section.
I want to use a tokenhash and expiry date in the Users DB so that it cant be abused, users would need to enter username and email to get an activation link emailed to them with a newly generated tokenhash
There are quite a few tutorials out there but I find most of them work for the first part e.g. emailing the activation link/ resetting token and timer but all seem to fail on the change of the password.
Please help me, either with a working tutorial from the net or a solution that applies the above required things.
Thanks in advance
Steve
Below I am writing the code that I wrote for one of my project, this might help you out.
1- I created a new table which contains the unique token for every user.
Table Name:- user_password_resets
Columns : userclient_id, token
2- A email template name as:- change_password.html inside /webroot/template/change_password.html
public function login_send() {
$this->isLoggedIn(); //Check if the user is logged in
if($this->request->is('post')) { #if the form is submitted
$login = $this->data['User']['login'];
$conditions = array('User.login'=>$login);
if($this->User->hasAny($conditions)) {
$users = $this->User->find('first', array('conditions'=>$conditions));
#Generate the token
$token = md5(uniqid(rand(),true));
#Save token and other details in user_password_reset_links table
$users = $this->User->find('first', array('conditions'=>array('User.login'=>$login)));
$my_name = $users['User']['first_name'];
$reset_links = array();
$reset_links['UserPasswordReset']['userclient_id'] = $users['User']['client_id'];
$reset_links['UserPasswordReset']['token'] = $token;
$conditions = array('UserPasswordReset.userclient_id'=>$users['User']['client_id']);
if($this->UserPasswordReset->hasAny($conditions)) {
$user_id = $users['User']['client_id'];
$this->UserPasswordReset->updateAll(array('UserPasswordReset.token'=>"'$token'"), array("UserPasswordReset.userclient_id"=>"$user_id"));
} else {
$this->UserPasswordReset->create();
$this->UserPasswordReset->save($reset_links);
}
$password_reset_link = BASE_URL."users/reset_password/$token";
#Send Welcome Email
$mailContent = file_get_contents(BASE_URL . "templates/change_password.html");
$rootlink = BASE_URL;
$arrMail = array(
"{NICK}" => ucfirst($my_name),
"{rootlink}" => BASE_URL,
"{SITE_TITLE}" => SITE_TITLE,
"{PASSWORD_RESET_LINK}"=>$password_reset_link
);
$mails = explode(',', $users['User']['email']);
$msg = #str_replace(array_keys($arrMail), array_values($arrMail), $mailContent);
$data = array();
$data['to'] = #$mails[0];
$data['body'] = $msg;
$data['subject'] = SITE_TITLE.'- Reset Password.';
$this->send_mail($data);
$this->Session->setFlash('A password reset link has been sent to the email address.', 'default', array('class'=>'successMsg'));
$this->redirect(array('controller'=>'users', 'action'=>'login'));
exit;
} else {
$this->Session->setFlash('The Username entered is not registered with Captain Marketing.', 'default', array('class'=>'errorMsg'));
$this->redirect(array('controller'=>'users', 'action'=>'login_send'));
exit;
}
}
$this->set('title_for_layout', '-Send password reset link');
}

Resources