File update laravel 8 Undefined variable: filename and filepath - variables

I want to upload a blogger's profile image but I get an error:
Undefined variable: filename
Undefined variable: filepath
I think it is a controller issue. I don't know why the variable is not defined, though I declared the same variable name.
So please help me out.
public function update(Request $request)
{
$this->validate($request, [
'id' => 'required',
'company' => 'required',
'period' => 'required',
'desc' => 'required',
// 'file' => 'required|mimes:txt,xlx,xls,pdf,jpg,png|max:6048',
]);
$id = $request->id;
$send = Setting_product::findOrFail($id);
if($request->file()) {
$fileName = time().'_'.$request->file->getClientOriginalName();
$filePath = $request->file('file')->storeAs('files/'.$request->company.'/TC', $fileName, 'public');
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc,
'term_condition_file_path' => $filePath,
'term_condition_file' => $fileName,
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}else{
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}
}

public function update(Request $request)
{
$this->validate($request, [
'id' => 'required',
'company' => 'required',
'period' => 'required',
'desc' => 'required',
'file' => 'required|mimes:txt,xlx,xls,pdf,jpg,png|max:6048',
]);
$id = $request->id;
$send = Setting_product::findOrFail($id);
if ($request->hasFile('file')) {
$fileName = time().'_'.$request->file->getClientOriginalName();
$filePath = $request->file('file')->storeAs('files/'.$request->company.'/TC', $fileName, 'public');
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc,
'term_condition_file_path' => $filePath,
'term_condition_file' => $fileName,
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}else{
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}
}

Related

Cakephp 4 save delete auto_increment

I'm doing cakephp4 controller test with phpUnit but when I call save my id auto_increment disapear.
My table before save():
Image before save
The test:
public function testAdd(): void
{
$this->session([
'Auth' => [
'id' => 1,
'DNI_CIF' => '22175395Z',
'name' => 'Prueba',
'lastname' => 'Prueba Prueba',
'username' => 'Pruebatesting',
'password' => 'prueba',
'email' => 'prueba#gmail.com',
'phone' => '639087621',
'role' => 'admin',
'addres_id' => 1
]
]);
$this->get('animal/add');
$this->assertResponseOk();
$data=[
'id' => 1,
'name' => 'AñadirAnimal',
'image' => '',
'specie' => 'dog',
'chip' => 'no',
'sex' => 'intact_male',
'race' => 'cat',
'age' => 1,
'information' => 'Es un animal.',
'state' => 'sick',
'animal_shelter' => [
'id' => 1,
'start_date' => '2022-11-03 10:47:38',
'end_date' => '2022-11-03 10:47:38',
'user_id' => 1,
'animal_id' => 1
]
];
$this->enableCsrfToken();
$this->post('animal/add',$data);
$this->assertResponseOk();
}
The controller:
public function add()
{
$animal = $this->Animal->newEmptyEntity();
if ($this->request->is('post')) {
$animal = $this->Animal->patchEntity($animal, $this->request->getData());
if(!$animal->getErrors){
$image = $this->request->getData('image_file');
if($image !=NULL){
$name = $image->getClientFilename();
}
if( !is_dir(WWW_ROOT.'img'.DS.'animal-img') ){
mkdir(WWW_ROOT.'img'.DS.'animal-img',0775);
if($name){
$targetPath = WWW_ROOT.'img'.DS.'animal-img'.DS.$name;
$image->moveTo($targetPath);
$animal->image = 'animal-img/'.$name;
}
}
if ($this->Animal->save($animal)) {
$this->Flash->success(__('El animal se ha añadido.'));
return $this->redirect(['action' => 'index']);
}
}
$this->Flash->error(__('El animal no se ha podido añadir, por favor intentalo de nuevo'));
}
$allUsers = $this->getTableLocator()->get('User');
$user = $allUsers->find('list', ['limit' => 200])->all();
$this->set(compact('animal','user'));
}
My table after:
Image after save
The error:
1) App\Test\TestCase\Controller\AnimalControllerTest::testAdd
Possibly related to PDOException: "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value"
…
Failed asserting that 500 is between 200 and 204.
I don't know why this is happening or how to know the reason. In the app the controller works fine. Data in the app:
Data in app
Data in test:
Data in test
I hope someone can help me, I don't know what to try anymore or how to know where the problem is...
I tried to look at the data but it doesn't apear to have any errors so I don't know where the error can be.
It was that the sql file used in the bootstrap didn't have the autoincrement value.

How to make array taking data from database in laravel

why this is not working where all my queries are individually working.
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
this works manually like
$data = [
'name' => 'my_name',
'email' => 'my_email',
'phone' => 'my_phone',
'address' => 'my_address',
'gender' => 'my_gender',
];
return $data;
my whole function is given below:
public function read($id){
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->get();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->get();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
When using get() it returns a collection not a single object so you can do
public function read($id){
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->first();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->first();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
Or if you have relations defined on the models you can use the relation
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
public function read($id)
{
$user = User::with('profile')->findOrFail($id);
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $user->profile->phone,
'address' => $user->profile->address,
'gender' => $user->profile->gender
];
return $data;
}

Change Password in hashed function in laravel 5.6

I want to change my password which is been hashed while saving.
How can i change the password?
'password' => Hash::make($data->password).
My Controller
$request->validate([
'oldpass' => 'required',
'password' => 'required|alphaNum|min:6',
'password_confirmation' => 'required|same:newpass',
]);
$id = $request->id;
$users = Auth::user()->whereId($id)->get();
foreach ($users as $user) {
if ($oldpass == $user->password) {
$user->update([
'password' => Hash::make($request->newpass)
]);
return view('\balance');
} else {
return 'error';
}
}
You should use Hash::check($old_password, $hashed_password), something like this:
public function passwordChange(Request $request, User $user_name) {
// find the loggedin user
$user = User::find(Auth::user()->id);
// validate rules
$validator = Validator::make($request->all(), [
'old_password' => 'required|min:6',
'password' => 'required_with:password_confirmation|required|min:6',
'password_confirmation' => 'confirmed|required|min:6',
]);
// what to do if validator fails
if ($validator->fails()) {
return redirect($user->user_name . '/settings')->withErrors($validator)->withInput();
} else {
$old_password = $request->input('old_password');
$new_password = $request->input('password');
$hashed_password = Auth::user()->password;
// checking the old pass with new one
if (Hash::check($old_password, $hashed_password)) {
$user->update([
'password'=> Hash::make($new_password)
]);
return redirect($user->user_name . '/settings')->with('success', 'Your Password updated.');
} else {
return redirect($user->user_name . '/settings')->with('success', 'Your Old password is wrong!');
}
}
}
Please also notice 'password' => 'required_with:password_confirmation and 'password_confirmation' => 'required|same:newpass' on validator. Hope it helps.

How actionError() function will call in my controller in yii2?

backend/controllers/AccessController.php
public function actionFault(){
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
$statusCode = $exception->statusCode;
$name = $exception->getName();
$message = $exception->getMessage();
$this->layout = 'layout';
return $this->render('error', [
'exception' => $exception,
'statusCode' => $statusCode,
'name' => $name,
'message' => $message
]);
}
backend/config/main.php
'components' => [
// ...
'errorHandler' => [
'errorAction' => 'access/fault',
],
// ...
],
If I am not wrong than actionError() will call when any error comes am i right ?
But in my case actionError is not calling what i am doing wrong ?

Strange CakePHP 2.0 auth login issue

Ok, so I was having a very interesting issue with CakePHP 1.3, in that even if I used the correct information to try to log in, it wouldn't work. I've now upgraded the same app to Cakephp 2.0, and I'm having a very different issue. Basically now, regardless of what information I put in when I'm logging in, it will log in. Even if the database is empty. No idea why this is happening...
Here's my code:
View:
<div id="login">
<p>Please log in! <a id="register" href="register" alt="Register">Register</a></p>
<hr class="login"/>
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo "<hr class=\"login\"/>";
echo $this->Form->end('Login');
echo $this->Session->flash('flash_registration');
echo "<pre>"; print_r($this->request->data); echo "</pre>";
echo $this->Html->link('Log-Out', 'logout');
?>
</div>
Model:
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'custom_rule' => array(
'rule' => '/^[A-Za-z\s]*$/i',
'message' => 'Please enter an acceptable name'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'dob' => array(
'rule' => array('date', 'ymd'),
'message' => 'Enter a valid date',
),
'phone' => array(
'numbers' => array(
'rule' => 'numeric',
'message' => 'Numbers only, no dashes or spaces'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'message' => 'Letters and numbers only'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'e-mail' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please enter a valid e-mail address'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'password_enter' => array(
'length' => array(
'rule' => array('between', 8, 16),
'message' => 'Password must be between 8 and 16 characters'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'password_confirm' => array(
'identicalFieldValues' => array(
'rule' => array('identicalFieldValues', 'password_enter'),
'message' => 'Passwords do not match'
),
'length' => array(
'rule' => array('between', 8, 16),
'message' => 'Password must be between 8 and 16 characters'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
)
);
function identicalFieldValues( $field=array(), $compare_field=null ){
foreach( $field as $key => $value ){
$v1 = $value;
$v2 = $this->data[$this->name][ $compare_field ];
if($v1 !== $v2) {
return FALSE;
} else {
return TRUE;
}
}
}
function beforeValidate(){
$this->data['User']['dob'] = $this->data['User']['dob'];
return true;
}
function beforeSave(){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password_enter']);
$this->data['User']['activated'] = FALSE;
return TRUE;
}
}
?>
Controller:
<?php
class UsersController extends AppController {
var $name = 'Users';
var $uses = array("User");
var $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);
var $helpers = array('Form', 'Session', 'Html');
function beforeFilter(){
// Basic setup
$this->Auth->authenticate = array('Form');
$this->Auth->allow('register', 'activate');
}
function index() {
}
function login() {
$this->Auth->login($this->request->data);
$this->set('title_for_layout', "Welcome to Sound-On.com!");
$this->layout = 'user_functions';
if ($this->Auth->user()) {
echo "Logged in!";
} else {
echo "Not logged in!";
}
}
function logout() {
$this->redirect($this->Auth->logout());
}
function register(){
$this->set('title_for_layout', "Register Here!");
$this->layout = 'user_functions';
$date = date('Y');
if (!empty($this->data)) {
$user_check = $this->User->find('first', array('conditions' => array('username' => $this->data['User']['username'])));
$email_check = $this->User->find('first', array('conditions' => array('e-mail' => $this->data['User']['e-mail'])));
if (empty($user_check)) {
if(empty($email_check)){
if ($this->User->save($this->data)) {
$uuid_string = $this->data['User']['activation_hash'];
$email = <<<EOT
<html>
<head>
<title>Welcome to Sound-On.com!</title>
</head>
<body>
<p>
<h1>Welcome to Sound-on.com!</h1>
<p>You have successfully registered! To activate your account and start sounding on, please click Here! <br/>If the link is not clickable, please copy and paste the link below into your browser address bar.</p>
http://www.sound-on.com/activate?uid=$uuid_string
<p style="">Thank you for registering!</p>
<p>Your friendly Sound-On registration robot</p>
<p>If you did not register or wish to remove your account, please click here.</p>
<p style="font-size:8pt;color:#707070">© Copyright $date Sound-on.com. All rights Reserved.</p>
</p>
</body
</html>
EOT;
$to = $this->data['User']['e-mail'];
$subject = 'Welcome to Sound-On.com!';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: registration#Sound-On.com';
if (mail($to, $subject, $email, $headers)) {
$this->redirect('/');
}
} else {
//$this->Session->setFlash('<p class="register_flash">Something went wrong. Please try again.</p>', 'flash_registration');
//$this->flash('', '/');
}
} else {
//email exists
}
} else {
//username exists
}
}
}
function activate(){
$this->set('title_for_layout', "Register Here!");
$this->layout = 'user_functions';
if (!empty($_GET)) {
$activate = $this->User->updateAll(array('activated' => 1), array('activation_hash' => $_GET['uuid']));
if ($activate) {
$this->set('message', '<p id="activation_message">Your account has been successfully activated! Please click here to proceed to login!</p>');
}
}
}
}
?>
Thanks in advance!
If you send data to the Auth->login() function it will log in with the data.
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
You need to use something like this.
public function login() {
if ($this->request->is('post')) {
if (!$this->Auth->login()) {
$this->Session->setFlash('Your username or password was incorrect.');
} else {
$this->Session->setFlash('You are now logged in.');
//redirect
}
}
}