Ambiguous class resolution in laravel phpexcel update - php

I try to update the laravel with php excel while installing i found the below warning in the composer.
Error:
Warning: Ambiguous class resolution, "SettingsController" was found in both
"C:\xampp\htdocs\mti\app\controllers\SettingsController.php" and
"C:\xampp\htdocs\mti\app\controllers\SettingsControllerBackup.php", the first
will be used.Warning: Ambiguous class resolution, "ClassModel" was found in both
"C:\xampp\htdocs\mti\app\models\ClassModel.php" and "C:\xampp\htdocs\mti\
app\models\LoginModel.php", the first will be used.
SettingsController:
<?php
class SettingsController extends BaseController
{
public function ChangePasswordLayout()
{
return View::make('settings/changepassword/changepassword');
}
public function ChangePasswordProcess()
{
$PasswordData = Input::all();
Validator::extend('pwdvalidation', function($field, $value, $parameters)
{
return Hash::check($value, Auth::user()->password);
});
$messages = array('pwdvalidation' => 'The Old Password is Incorrect');
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes())
{
$user = User::find(Auth::user()->id);
$user->password = Hash::make(Input::get('NewPassword'));
$user->save();
return Redirect::to('changepassword')->withInput()->with('Messages', 'The Password Information was Updated');
} else
{
return Redirect::to('changepassword')->withInput()->withErrors($validator);
}
}
public function ProfileLayout()
{
$user = Auth::user()->id;
$ProfileDetailsbyid = ProfileModel::where('id', $user)->get()->toArray();
return View::make('settings/profile/profile')->with('ProfileDetailsbyid', $ProfileDetailsbyid);
}
public function ProfileUpdateProcess($data=NULL)
{
$user = Auth::user()->id;
$ProfileDetailsbyid = ProfileModel::where('id', $user)->get()->toArray();
$ProfileData = array_filter(Input::except(array('_token')));
$validation = Validator::make($ProfileData, ProfileModel::$rules);
if ($validation->passes())
{
if(!empty($ProfileData['Photo']))
{
Input::file('Photo')->move('assets/uploads/profilephoto/', $user . '-Photo.' . Input::file('Photo')->getClientOriginalName());
$Photo=$user.'-Photo.' . Input::file('Photo')->getClientOriginalName();
unset($ProfileData['Photo']);
$ProfileData['Photo']=$Photo;
}
$affectedRows = ProfileModel::where('id', $user)->update($ProfileData);
//VehicleModel::create($VehicleData);
return Redirect::to('profile')->with('Message', 'Profile Details Update Succesfully')->with('ProfileDetailsbyid', $ProfileDetailsbyid);
} else
{
return Redirect::to('profile')->withInput()->withErrors($validation->messages())->with('ProfileDetailsbyid', $ProfileDetailsbyid);
}
}
}
ClassModel:
<?php
class ClassModel extends Eloquent
{
protected $primaryKey = 'AutoID';
protected $created_at = 'CreatedAt';
protected $updated_at = 'UpdatedAt';
protected $table = 'class';
protected $guarded = array('GradeName');
protected $fillable = array('GradeName');
public function batch(){
return $this->hasMany('BatchModel', 'Class');
}
public function studentadmissionresult(){
return $this->hasMany('StudentAdmissionModel', 'StudentCourse');
}
public $timestamps = true;
public static $rules = array(
'GradeName' => array('required', 'unique:class','regex:/^./'),
'GradeSection' => 'required',
'GradeCode' => array('required', 'unique:class')
);
public static $updaterules = array(
'GradeName' => array('required','regex:/^./'),
'GradeSection' => 'required',
'GradeCode' => array('required')
);
}
I following this tutorial:
https://github.com/Maatwebsite/Laravel-Excel
I have try following command :
composer require maatwebsite/excel": "~1.2.1

This actually has nothing to do with the package you are installing.
Explanation
When recreating the autoload files (composer dump-autoload) after the update Composer detected that you have two classes with the exact same name (but in different files).
Class SettingsController in SettingsController.php and SettingsControllerBackup.php
and class ClassModel in ClassModel.php and LoginModel.php
Composer will then choose to use one of the two (I'm not sure how it makes that decision, it's probably just the first one it finds) and will ignore the other occurrence. - Confirmed. Composer uses first match.
Solutions
Delete the files if you don't need them
Rename the class
A good and common practice is to name the class like the file. This is a simple way to avoid such collisions because two files in the same directory can't have the same name.

Related

Codeigniter 4 ignoring model insert callback

Running model->insert() from my controller does not trigger the beforeInsert function, below is my model and the function from my conntroller
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model {
protected $table = 'admin_users';
protected $useAutoIncrement = true;
protected $primaryKey = 'row_uid';
protected $returnType = 'object';
protected $beforeInsert = ['passwordHash'];
protected $allowCallbacks = true;
protected $allowedFields = ['id', 'row_uid', 'username', 'email', 'password', 'active', 'deleted_at'];
public function __construct() {
return $this;
}
protected function passwordHash($data) {
$data['data']['row_uid'] = uniqid('',true);
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
if(isset($data['data']['password_c'])) unset($data['data']['password_c']);
return $data;
}
}
And here is the controller function
public function postRegister() {
$request = \Config\Services::request();
if($post = $request->getPost()) {
$valid = $this->validate([
'username' => 'is_unique[admin_users.username]', // Change table name to be dynamic
'email' => 'required|valid_email|is_unique[admin_users.email]', // Change table name to be dynamic
'password' => 'required|min_length[10]|max_length[100]',
'password_c' => 'required|matches[password]',
]);
if(!$valid) {
$this->data['errors'] = $this->validator->getErrors();
foreach($post as $key => $e) {
if(isset($this->data['errors'][$key])) {
$this->data['invalid_fields'][$key] = ' is-invalid';
} else $this->data['invalid_fields'][$key] = '';
}
return $this->getRegister();
}
$l = $this->userModel->insert($post);
echo '<pre>',var_dump($l),'</pre>';exit;
}
}
I determine that the callback is not running because the password is not hashed, the uid is not generated and running die or exit does nothing.
Thank you
EDIT:
I got it working by adding allowCallback() but i shouldn't need this?
$this->userModel->allowCallbacks(true)->insert($post);
1 - Delete the constructor method in the model; you don't need that .
2- set protected $allowCallbacks = true; before $beforeInsert = ['passwordHash'];
The above approach is standard coding in the Codeigniter framework. If those steps didnt resolve the problem, the solution is to check the database for the row_uid and password types.

laravel syntax error unexpected '.' on attempted concatenation of string in model

I am working in Laravel, and I have a model Group where I have rules for validation. I am attempting to have a unique name_group but only for the given year. The code below works perfectly if I replace .$this->year_groups with 2016 for example. But when I try to add the actual year of the group to be created by concatenating .this->year_groups, I get a syntax error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException syntax error, unexpected '.', expecting ')'
I have looked at many examples and they (seem) to be written this way, and I just can't find what is wrong. I am thinking perhaps it has something to do that this is in an array...?
Any help would be greatly appreciated!!
Model:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//The error is in the following $rules
public static $rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $this->year_groups,
'grados_id_grados' => 'required'
);
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
In the Controller I call validation from the store method:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::$rules);
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}
Looking your code, it seems $rules is variable or property of class. The way you are assigning values to property are wrong, so it is throwing error. Look below code and arrange your code accordingly:-
class anyClass {
private $year_groups = "2016";
public $rules = [];
public function __construct(){
$this->rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,'.$this->year_groups,
'grados_id_grados' => 'required'
);
}
}
I changed Model to:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//This part I changed
public static $rules = [];
public static function _construct($year){
$rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $year,
'grados_id_grados' => 'required'
);
return $rules;
}
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
Then in Controller:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::_construct(Input::get('year_groups')));
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}

How to pass and retrieve data between two controllers in Laravel

I'm trying to get to grips with Laravel and not finding the documentation any help at all. It seems to assume you know so much instead of actually walking new users through each section step by step.
I've got to the point where I need to make an internal call to another class, and sticking with MVC I can't seem to do what should be a simple thing.
My code:
class UsersController extends BaseController {
protected $layout = 'layouts.templates.page';
protected $messages;
public function getIndex()
{
$input = array('where', array('field' => 'email', 'operator' => '=', 'value' => 'tony#fluidstudiosltd.com'));
$request = Request::create('user/read', 'GET');
$users = json_decode(Route::dispatch($request)->getContent());
var_dump($users); exit;
$this->pageTitle = 'Fluid Customer Status :: Admin Users';
$this->content = View::make('layouts.admin.users');
}
}
Class UserController extends Base Controller
public function getRead()
{
$userId = (int) Request::segment(3);
if ($userId)
{
$user = User::findOrFail($userId);
return $user;
}
else
{
$users = new User;
var_dump(Input::all()); exit;
if (Input::has('where'))
{
var_dump(Input::get('where')); exit;
}
return $users->get();
}
}
Why isn't the input data from UsersController#getIndex available in UserController#getRead

Laravel 4 Unique Validation Rules Not Working

need help updating a unique rule in my validation rules. I have a abstract validator that will validate a rules before storing into my database and in the rules array I set the email to be unique when creating or registering a user but when updating the user the enique email should not validate if the email is owned by the user.
abstract class Validator
abstract class Validator {
protected $errors;
protected $attributes;
public function __construct($attributes = null)
{
$this->attributes = $attributes ?: \Input::all();
}
public function passes()
{
$validation = \Validator::make($this->attributes, $this->rules());
if ($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
public function getErrors()
{
return $this->errors;
}
}
Validation Rules(UserRule.php)
use MyCustomValidatorNamespaceHere....
class UserRules extends Validator
public function rules()
{
return [
'email' => 'required|email|unique:users,email,id',
...
];
}
and in my UserController I injected the UserRule in the constractor. (UserRule $userRule). Here is the code in the update method.
public function update($id)
{
$if ($this->userRule->passes())
{
$this->user->find($id)->update(Input::all());
return .........
}
}
But the validation always fail and displaying the error that the email is already taken. Please help guys.
The problem is your rule. When you update, you need to use unique that doesn't check record you update. So you should have:
unique:users,email,id
but for example:
unique:users,email,10
if you edit record with id 10.
What you could do is to define this rule:
'email' => 'required|email|unique:users,email,{id}',
and your passes method:
public function passes($id = null)
{
$rules = $this->rules();
$rules['email'] = str_replace('{id}', $id, $rules['email']);
$validation = \Validator::make($this->attributes, $rules);
if ($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
and now in update rule use:
if ($this->userRule->passes($id))
By the way you have error in $if ($this->userRule->passes()) - it should be if and not $if
You can use the route method inside your request class to except an id from the validation
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->route('user'),
...
];
}
I had a problem like that before and it was difficult to find an answer. Here is what I did.
class UserRules extends Validator {
public function __construct($input = NULL) {
$this->input = $input ?: \Input::all();
if(isset($this->input['id'])):
self::$rules['username'] = 'required|unique:users,username,'.$this->input['id'];
self::$rules['email'] = 'required|email|unique:users,email,'.$this->input['id'];
else:
self::$rules['username'] = 'required|unique:users';
self::$rules['email'] = 'required|email|unique:users';
endif;
}
public static $rules = array(
'company_id' => 'required',
'role' => 'required',
'password' => 'sometimes|required|confirmed'
);
}
You need to use self:: because $rules is static.
I have moved this function:
public function passes($id)
{
$rules = static::$rules;
$rules['username'] = str_replace('{id}', $id, $rules['username']);
$rules['email'] = str_replace('{id}', $id, $rules['email']);
$validation = \Validator::make($this->attributes, $rules);
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
into UserRule.php and commented the same function in abstract class Validator
Now updating is working.
I solved this problem here on stackoverflow in a generic way. It will automatically adapt your rules if you do an update and add exceptions to your :unique if necessary.

How to create new user in Laravel?

I created the model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class ClientModel extends Eloquent implements UserInterface, RemindableInterface {
protected $connection = 'local_db';
protected $table = 'administrators';
protected $fillable = ['user_id'];
public function getAuthIdentifier()
{
return $this->username;
}
public function getAuthPassword()
{
return $this->password;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getReminderEmail()
{
return $this->email;
}
}
When I try to use it like this:
ClientModel::create(array(
'username' => 'first_user',
'password' => Hash::make('123456'),
'email' => 'my#email.com'
));
It creates empty entry in DB...
I think you make it too complicated. There is no need to make it this way. By default you have User model created and you should be able simple to create user this way:
$user = new User();
$user->username = 'something';
$user->password = Hash::make('userpassword');
$user->email = 'useremail#something.com';
$user->save();
Maybe you wanted to achieve something more but I don't understand what you use so many methods here if you don't modify input or output here.
You are using create method (Mass Assignment) so it's not working because you have this:
// Only user_id is allowed to insert by create method
protected $fillable = ['user_id'];
Put this in your model instead of $fillable:
// Allow any field to be inserted
protected $guarded = [];
Also you may use the alternative:
protected $fillable = ['username', 'password', 'email'];
Read more about Mass Assignment on Laravel website. While this may solve the issue but be aware of it. You may use this approach instead:
$user = new User;
$user->username = 'jhondoe';
// Set other fields ...
$user->save();
Nowadays way :
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
or even:
$arrLcl = [];
$arrLcl['name'] = $data['name'];
$arrLcl['email'] = $data['email'];
$arrLcl['password'] = $data['password'];
User::create($arrLcl);

Categories