Form Doesn't Post Value in OrangeHRM - php

I create new module on OrangeHRM and try to create a form. But when i post the form, the values doesn't post to action file. I've tried many times, but the result still same.
here is the action:
<?php
class requestTrainingAction extends sfAction {
private $trainingService;
/**
* Get TrainingService
* #returns TrainingService
*/
public function getTrainingService() {
if (is_null($this->trainingService)) {
$this->trainingService = new TrainingService();
}
return $this->trainingService;
}
/**
* Set TrainingService
* #param TrainingService $trainingService
*/
public function setTrainingService(TrainingService $trainingService) {
$this->trainingService = $trainingService;
}
/**
* #param sfForm $form
* #return
*/
public function setForm(sfForm $form) {
if (is_null($this->form)) {
$this->form = $form;
}
}
/**
*
* #param <type> $request
*/
public function execute($request) {
/* For highlighting corresponding menu item */
$request->setParameter('initialActionName', 'requestTraining');
$this->form = new RequestTrainingForm();
if ($this->getUser()->hasFlash('templateMessage')) {
$this->templateMessage = $this->getUser()->getFlash('templateMessage');
}
if ($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid()) {
$templateMessage = $this->form->save();
$this->getUser()->setFlash($templateMessage['messageType'], $templateMessage['message']);
$this->redirect('training/requestTraining');
}
}
$this->listForm = new DefaultListForm();
}
}
?>
Here is the form:
<?php
class RequestTrainingForm extends BaseForm {
private $trainingService;
private $trainingId;
public function getTrainingService() {
if (is_null($this->trainingService)) {
$this->trainingService = new TrainingService();
}
return $this->trainingService;
}
public function setTrainingService(TrainingService $trainingService) {
$this->trainingService = $trainingService;
}
public function configure() {
// Job Level
$jobLevelChoices = Training::getLevelTextList();
$divisionChoices = Training::getDivisionTextList();
$departmentChoices = Training::getDepartmentTextList();
$this->setWidgets(array(
'chkJobLevel' => new ohrmWidgetCheckboxGroup(array('choices' => $jobLevelChoices, 'show_all_option' => true)),
'chkDivision' => new ohrmWidgetCheckboxGroup(array('choices' => $divisionChoices, 'show_all_option' => true)),
'chkDepartment' => new ohrmWidgetCheckboxGroup(array('choices' => $departmentChoices, 'show_all_option' => true)),
'training_name' => new sfWidgetFormInputText(),
'training_desc' => new sfWidgetFormTextArea(),
));
$this->setValidators(array(
'chkJobLevel' => new sfValidatorChoice(array('choices' => array_keys($jobLevelChoices), 'required' => true, 'multiple' => true)),
'chkDivision' => new sfValidatorChoice(array('choices' => array_keys($divisionChoices), 'required' => true, 'multiple' => true)),
'chkDepartment' => new sfValidatorChoice(array('choices' => array_keys($departmentChoices), 'required' => true, 'multiple' => true)),
'training_name' => new sfValidatorString(array('required' => true, 'max_length' => 120)),
'training_desc' => new sfValidatorString(array('required' => false, 'max_length' => 400)),
));
$this->widgetSchema->setNameFormat('training[%s]');
}
/**
*
* #return array
*/
public function getStylesheets() {
$styleSheets = parent::getStylesheets();
return $styleSheets;
}
public function getJavaScripts() {
$javaScripts = parent::getJavaScripts();
$javaScripts[] = plugin_web_path('orangehrmTrainingPlugin', 'js/requestTrainingSuccess.js');
return $javaScripts;
}
public function save() {
$message = array('messageType' => 'success', 'message' => __(TopLevelMessages::SAVE_SUCCESS));
$training = new Training();
$training->setTrainingName($this->getValue('training_name'));
$training->setTrainingDesc($this->getValue('training_desc'));
$this->getTrainingService()->saveRequestTraining($training);
return $message;
}
}
?>
And here the DAO:
<?php
class TrainingDao extends BaseDao {
public function saveRequestTraining(Training $training) {
try {
$training->save();
return $training;
} catch (Exception $e) {
throw new DaoException($e->getMessage(), $e->getCode(), $e);
}
}
}
?>
The error show this:
01/06/17 11:21:16,781 [644] ERROR filter.ExceptionCatcherFilter - Uncaught Exception: exception 'Doctrine_Validator_Exception' with message 'Validation failed in class Training
2 fields had validation errors:
* 1 validator failed on trainingName (unsigned)
* 1 validator failed on trainingDesc (unsigned)
' in C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Transaction.php:265
Stack trace:
#0 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Connection.php(1395): Doctrine_Transaction->commit(NULL)
#1 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Connection\UnitOfWork.php(148): Doctrine_Connection->commit()
#2 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Record.php(1718): Doctrine_Connection_UnitOfWork->saveGraph(Object(Training))
#3 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\lib\dao\TrainingDao.php(7): Doctrine_Record->save()
#4 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\lib\service\TrainingService.php(43): TrainingDao->saveRequestTraining(Object(Training))
#5 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\lib\form\RequestTrainingForm.php(79): TrainingService->saveRequestTraining(Object(Training))
#6 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\modules\training\actions\requestTrainingAction.class.php(87): RequestTrainingForm->save()
#7 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(952): requestTrainingAction->execute(Object(sfWebRequest))
#8 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmCorePlugin\lib\filter\orangehrmExecutionFilter.php(36): sfExecutionFilter->executeAction(Object(requestTrainingAction))
#9 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(947): orangehrmExecutionFilter->executeAction(Object(requestTrainingAction))
#10 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(933): sfExecutionFilter->handleAction(Object(sfFilterChain), Object(requestTrainingAction))
#11 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfExecutionFilter->execute(Object(sfFilterChain))
#12 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\filter\sfCommonFilter.class.php(29): sfFilterChain->execute()
#13 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfCommonFilter->execute(Object(sfFilterChain))
#14 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmCorePlugin\lib\filter\orangehrmPostExecutionFilter.php(22): sfFilterChain->execute()
#15 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): orangehrmPostExecutionFilter->execute(Object(sfFilterChain))
#16 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\ModuleFilter.php(56): sfFilterChain->execute()
#17 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): ModuleFilter->execute(Object(sfFilterChain))
#18 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmCorePlugin\lib\authorization\filter\ohrmAuthorizationFilter.php(97): sfFilterChain->execute()
#19 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): ohrmAuthorizationFilter->execute(Object(sfFilterChain))
#20 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\SessionInfoFetcherFilter.php(67): sfFilterChain->execute()
#21 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): SessionInfoFetcherFilter->execute(Object(sfFilterChain))
#22 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\OrangeI18NFilter.php(58): sfFilterChain->execute()
#23 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): OrangeI18NFilter->execute(Object(sfFilterChain))
#24 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\ExceptionCatcherFilter.php(26): sfFilterChain->execute()
#25 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): ExceptionCatcherFilter->execute(Object(sfFilterChain))
#26 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\filter\sfBasicSecurityFilter.class.php(72): sfFilterChain->execute()
#27 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfBasicSecurityFilter->execute(Object(sfFilterChain))
#28 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(995): sfFilterChain->execute()
#29 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfRenderingFilter->execute(Object(sfFilterChain))
#30 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(665): sfFilterChain->execute()
#31 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(2352): sfController->forward('training', 'requestTraining')
#32 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\util\sfContext.class.php(170): sfFrontWebController->dispatch()
#33 C:\xampp\htdocs\orangehrm-3.2.1\symfony\web\index.php(22): sfContext->dispatch()
#34 {main}
Next exception 'DaoException' with message 'Validation failed in class Training
2 fields had validation errors:
* 1 validator failed on trainingName (unsigned)
* 1 validator failed on trainingDesc (unsigned)
' in C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\lib\dao\TrainingDao.php:11
Stack trace:
#0 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\lib\service\TrainingService.php(43): TrainingDao->saveRequestTraining(Object(Training))
#1 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\lib\form\RequestTrainingForm.php(79): TrainingService->saveRequestTraining(Object(Training))
#2 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmTrainingPlugin\modules\training\actions\requestTrainingAction.class.php(87): RequestTrainingForm->save()
#3 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(952): requestTrainingAction->execute(Object(sfWebRequest))
#4 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmCorePlugin\lib\filter\orangehrmExecutionFilter.php(36): sfExecutionFilter->executeAction(Object(requestTrainingAction))
#5 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(947): orangehrmExecutionFilter->executeAction(Object(requestTrainingAction))
#6 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(933): sfExecutionFilter->handleAction(Object(sfFilterChain), Object(requestTrainingAction))
#7 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfExecutionFilter->execute(Object(sfFilterChain))
#8 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\filter\sfCommonFilter.class.php(29): sfFilterChain->execute()
#9 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfCommonFilter->execute(Object(sfFilterChain))
#10 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmCorePlugin\lib\filter\orangehrmPostExecutionFilter.php(22): sfFilterChain->execute()
#11 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): orangehrmPostExecutionFilter->execute(Object(sfFilterChain))
#12 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\ModuleFilter.php(56): sfFilterChain->execute()
#13 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): ModuleFilter->execute(Object(sfFilterChain))
#14 C:\xampp\htdocs\orangehrm-3.2.1\symfony\plugins\orangehrmCorePlugin\lib\authorization\filter\ohrmAuthorizationFilter.php(97): sfFilterChain->execute()
#15 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): ohrmAuthorizationFilter->execute(Object(sfFilterChain))
#16 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\SessionInfoFetcherFilter.php(67): sfFilterChain->execute()
#17 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): SessionInfoFetcherFilter->execute(Object(sfFilterChain))
#18 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\OrangeI18NFilter.php(58): sfFilterChain->execute()
#19 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): OrangeI18NFilter->execute(Object(sfFilterChain))
#20 C:\xampp\htdocs\orangehrm-3.2.1\symfony\apps\orangehrm\lib\filter\ExceptionCatcherFilter.php(26): sfFilterChain->execute()
#21 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): ExceptionCatcherFilter->execute(Object(sfFilterChain))
#22 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\filter\sfBasicSecurityFilter.class.php(72): sfFilterChain->execute()
#23 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfBasicSecurityFilter->execute(Object(sfFilterChain))
#24 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(995): sfFilterChain->execute()
#25 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(1031): sfRenderingFilter->execute(Object(sfFilterChain))
#26 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(665): sfFilterChain->execute()
#27 C:\xampp\htdocs\orangehrm-3.2.1\symfony\cache\orangehrm\prod\config\config_core_compile.yml.php(2352): sfController->forward('training', 'requestTraining')
#28 C:\xampp\htdocs\orangehrm-3.2.1\symfony\lib\vendor\symfony\lib\util\sfContext.class.php(170): sfFrontWebController->dispatch()
#29 C:\xampp\htdocs\orangehrm-3.2.1\symfony\web\index.php(22): sfContext->dispatch()
#30 {main}

Related

Unique validation on update Laravel

I have a Laravel application. I am performing the user information update function, but I can't bypass the validation check for the admin_email and admin_title fields in the tbl_admin database. I am using the following FormRequest:
<?php
namespace App\Http\Requests;
use App\Models\Admin;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Rule;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$admin_id = $this->route('admin.edit');
return [
'account_title_name' => ['required', 'email', Rule::unique('tbl_admin', 'admin_email')->ignore($admin_id)],
'account_titleshow_name' => 'required|max:40',
'account_password_name' => 'required|min:8|regex:/^(?=.*[A-Z])(?=.*[!##$%^&*()]).*$/',
'account_tell_name' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:10|max:10|unique:tbl_admin,admin_phone',
'account_roles_name' => 'required',
];
}
public function messages(){
return [
'account_title_name.required'=>':attribute là bắt buộc',
'account_title_name.email'=>':attribute không đúng định dạng email (Chứa #gmail.com)',
'account_title_name.max'=>':attribute vượt quá quy định :max',
'account_title_name.max'=>':attribute vượt quá quy định :max',
'account_title_name.unique'=>':attribute đã tồn tại',
'account_titleshow_name.required'=>':attribute là bắt buộc',
'account_titleshow_name.max'=>':attribute vượt quá quy định :max',
'account_password_name.required' => ':attribute là bắt buộc',
'account_password_name.min' => ':attribute có ít nhất :min ký tự',
'account_password_name.regex' => ':attribute phải chứa ký tự viết hoa và kí tự đặc biệt',
'account_tell_name.required'=>':attribute là bắt buộc',
'account_tell_name.min'=>':attribute phải đủ :min số',
'account_tell_name.max'=>':attribute vượt quá quy định :max số',
'account_tell_name.regex'=>':attribute không đúng định dạng',
'account_tell_name.not_regex'=>':attribute không đúng định dạng',
'account_tell_name.unique'=>':attribute đã tồn tại',
'account_roles_name.required' => ':attribute',
];
}
public function attributes(){
return [
'account_title_name'=>'Tên tài khoản',
'account_titleshow_name'=>'Tên hiển thị',
'account_password_name'=>'Mật khẩu',
'account_roles_name' => 'Chọn một quyền cho tài khoản',
'account_tell_name' => 'Số điện thoại',
];
}
protected function failedValidation(Validator $validator)
{
if($this->wantsJson())
{
$response = response()->json([
'status' => 0,
'error'=>$validator->errors()->toArray()//$validator->errors()
]);
}else{
$response = redirect()
//->route('guest.login')
->with('message', 'Ops! Some errors occurred')
->withErrors($validator);
}
throw (new ValidationException($validator, $response))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl());
}
}
I hope someone will help me fix this issue so that I can update the user information and save the data. Here is the code of my FormRequest.
1. Controller
public function Edit_user($admin_id)
{
$this->AuthLogin ();
$admin = Auth::user();
// Kiểm tra người dùng có phải là admin hay không
if($admin->admin_id) {
$edit_field = Admin::where('admin_id', $admin_id)->first();
$roles_show = AdminRole::where('admin_admin_id', $admin_id)->first();
}
return view('admin.users.form.edit_users', compact('roles_show','edit_field'));
}
public function Update_user(UserRequest $request, $admin_id)
{
$form_update = [
'admin_email' => $request->input('account_title_name'),
'admin_password' => md5($request->input('account_password_name')),
'admin_name' => $request->input('account_titleshow_name'),
'admin_phone' => $request->input('account_tell_name'),
//'admin_id' => $request->input('admin_id_name'),
];
$admin = Admin::whereid($admin_id )->update($form_update);
AdminRole::updateOrCreate(
['admin_admin_id' => $admin->admin_id],
['roles_id_roles' => $request->input('account_roles_name')]
);
Toastr::success('Cập nhật thành công', 'Thành công');
return response()->json(['status'=>1, 'msg'=>'Cập nhật thông tin người dùng thành công']);
}
2. Models Admin (Database tbl_admin)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use HasFactory;
protected $fillable = [
'admin_id','admin_email', 'admin_password', 'admin_name','admin_phone'
];
protected $primaryKey = 'admin_id';
protected $table = 'tbl_admin';
public function roles(){
return $this->belongsToMany('App\Models\Roles');
}
public function getAuthPassword(){
return $this->admin_password;
}
public function hasAnyRoles($roles){
if(is_array($roles)){
foreach($roles as $role){
if($this->hasRole($role)){
return true;
}
}
}else{
if($this->hasRole($roles)){
return true;
}
}
return false;
}
public function hasRole($role){
if($this->roles()->where('name',$role)->first()){
return true;
}
return false;
}
}
3. Routes
route::get('/edit-user/{admin_id}','App\Http\Controllers\UserController#Edit_user')->name('admin.edit');
route::post('/update-user/{admin_id}','App\Http\Controllers\UserController#Update_user');``
Change these
public function rules()
{
$admin_id = $this->route('admin.edit');
return [
'account_title_name' => ['required', 'email', Rule::unique('tbl_admin', 'admin_email')->ignore($admin_id)],
'account_titleshow_name' => 'required|max:40',
'account_password_name' => 'required|min:8|regex:/^(?=.*[A-Z])(?=.*[!##$%^&*()]).*$/',
'account_tell_name' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:10|max:10|unique:tbl_admin,admin_phone',
'account_roles_name' => 'required',
];
}
To this
public function rule()
{
$admin_id = // Get the id of the admin you wanted to update
return [
'account_title_name' = 'required', 'email', 'unique: tbl_admin,email,'.$admin_id,
'account_titleshow_name' => 'required|max:40',
'account_password_name' => 'required|min:8|regex:/^(?=.*[A-Z])(?=.*[!##$%^&*()]).*$/',
'account_tell_name' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:10|max:10|unique:tbl_admin,admin_phone'.$admin_id,
'account_roles_name' => 'required',
];
}
I followed the instructions as directed, but still failed and Laravel log reported an error (Column not found: 1054 Unknown column 'id' in 'tbl_admin'). Currently, I am using 'admin_id' as the primary key in the 'tbl_admin' table. I would appreciate any help with this issue.
you can access the parameters in the Update_User function by using the $this keyword.
then the rule() function is like this:
public function rules()
{
return [
'account_title_name' => "required|email|unique:tbl_admin,admin_email,{$this->admin_id}",
'account_titleshow_name' => 'required|max:40',
'account_password_name' => 'required|min:8|regex:/^(?=.*[A-Z])(?=.*[!##$%^&*()]).*$/',
'account_tell_name' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:10|max:10|unique:tbl_admin,admin_phone',
'account_roles_name' => 'required',
];
}
$this keyword also applies to fetch other fields, like $this->account_title_name, $this->account_titleshow_name.
.....
if you get error then you have to tell what the primary_key column.
then it can be solved like this:
'account_title_name' => "required|email|unique:tbl_admin,admin_email,{$this->admin_id},admin_id",
let me give details: unique:table_name,column_name,except_based_id,primary_key
My issue has not been resolved and this error appears in the Laravel log file
[previous exception] [object] (PDOException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' at C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Connection.php:368)
[stacktrace]
#0 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Connection.php(368): PDO->prepare('select count()...')
#1 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Connection.php(705): Illuminate\Database\Connection->Illuminate\Database\{closure}('select count()...', Array)
#2 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Connection.php(672): Illuminate\Database\Connection->runQueryCallback('select count()...', Array, Object(Closure))
#3 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Connection.php(376): Illuminate\Database\Connection->run('select count()...', Array, Object(Closure))
#4 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2414): Illuminate\Database\Connection->select('select count(*)...', Array, false)
#5 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2402): Illuminate\Database\Query\Builder->runSelect()
#6 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2936): Illuminate\Database\Query\Builder->Illuminate\Database\Query\{closure}()
#7 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2403): Illuminate\Database\Query\Builder->onceWithColumns(Array, Object(Closure))
#8 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2863): Illuminate\Database\Query\Builder->get(Array)
#9 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2791): Illuminate\Database\Query\Builder->aggregate('count', Array)
#10 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Validation\DatabasePresenceVerifier.php(55): Illuminate\Database\Query\Builder->count()
#11 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Validation\Concerns\ValidatesAttributes.php(856): Illuminate\Validation\DatabasePresenceVerifier->getCount('tbl_admin', 'admin_email', 'bao123#gmail.co...', '59', 'id', Array)
#12 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Validation\Validator.php(610): Illuminate\Validation\Validator->validateUnique('account_title_n...', 'bao123#gmail.co...', Array, Object(Illuminate\Validation\Validator))
#13 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Validation\Validator.php(416): Illuminate\Validation\Validator->validateAttribute('account_title_n...', 'Unique')
#14 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Validation\Validator.php(447): Illuminate\Validation\Validator->passes()
#15 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Validation\ValidatesWhenResolvedTrait.php(25): Illuminate\Validation\Validator->fails()
#16 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Providers\FormRequestServiceProvider.php(30): Illuminate\Foundation\Http\FormRequest->validateResolved()
#17 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Container\Container.php(1265): Illuminate\Foundation\Providers\FormRequestServiceProvider->Illuminate\Foundation\Providers\{closure}(Object(App\Http\Requests\UserRequest), Object(Illuminate\Foundation\Application))
#18 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Container\Container.php(1230): Illuminate\Container\Container->fireCallbackArray(Object(App\Http\Requests\UserRequest), Array)
#19 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Container\Container.php(1215): Illuminate\Container\Container->fireAfterResolvingCallbacks('App\\Http\\Reques...', Object(App\Http\Requests\UserRequest))
#20 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Container\Container.php(778): Illuminate\Container\Container->fireResolvingCallbacks('App\\Http\\Reques...', Object(App\Http\Requests\UserRequest))
#21 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(851): Illuminate\Container\Container->resolve('App\\Http\\Reques...', Array, true)
#22 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Container\Container.php(694): Illuminate\Foundation\Application->resolve('App\\Http\\Reques...', Array)
#23 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(836): Illuminate\Container\Container->make('App\\Http\\Reques...', Array)
#24 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\RouteDependencyResolverTrait.php(79): Illuminate\Foundation\Application->make('App\\Http\\Reques...')
#25 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\RouteDependencyResolverTrait.php(48): Illuminate\Routing\ControllerDispatcher->transformDependency(Object(ReflectionParameter), Array, Object(stdClass))
#26 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\RouteDependencyResolverTrait.php(28): Illuminate\Routing\ControllerDispatcher->resolveMethodDependencies(Array, Object(ReflectionMethod))
#27 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(41): Illuminate\Routing\ControllerDispatcher->resolveClassMethodDependencies(Array, Object(App\Http\Controllers\UserController), 'Update_user')
#28 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Route.php(262): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\UserController), 'Update_user')
#29 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Route.php(205): Illuminate\Routing\Route->runController()
#30 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Router.php(721): Illuminate\Routing\Route->run()
#31 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(128): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#32 C:\xampp\htdocs\bao-hanh-demo\app\Http\Middleware\AccessAdmin.php(23): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#33 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): App\Http\Middleware\AccessAdmin->handle(Object(Illuminate\Http\Request), Object(Closure))
#34 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php(50): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#35 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
#36 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php(78): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#37 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#38 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#39 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#40 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(121): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#41 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(64): Illuminate\Session\Middleware\StartSession->handleStatefulRequest(Object(Illuminate\Http\Request), Object(Illuminate\Session\Store), Object(Closure))
#42 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#43 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#44 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#45 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(67): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#46 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#47 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#48 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Router.php(723): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#49 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Router.php(698): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#50 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Router.php(662): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#51 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Routing\Router.php(651): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#52 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(167): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#53 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#54 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#55 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull.php(31): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#56 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull->handle(Object(Illuminate\Http\Request), Object(Closure))
#57 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#58 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TrimStrings.php(40): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#59 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TrimStrings->handle(Object(Illuminate\Http\Request), Object(Closure))
#60 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#61 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#62 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#63 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance->handle(Object(Illuminate\Http\Request), Object(Closure))
#64 C:\xampp\htdocs\bao-hanh-demo\vendor\fruitcake\laravel-cors\src\HandleCors.php(38): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#65 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Fruitcake\Cors\HandleCors->handle(Object(Illuminate\Http\Request), Object(Closure))
#66 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Http\Middleware\TrustProxies.php(39): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#67 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Http\Middleware\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#68 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#69 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(142): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#70 C:\xampp\htdocs\bao-hanh-demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(111): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#71 C:\xampp\htdocs\bao-hanh-demo\index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#72 {main}
"}

Error The GET method is not supported for this route. Supported methods: POST. when trying to use route without providing auth token

I've been facing this weird error... I set up my laravel passport auth, and login works and provides a token. I'm trying to 'guard' my routes so that only logged in users can access them. I am using 'auth:api' middleware, when a token is provided everything goes well as it should but when it's not I keep getting 'The GET method is not supported for this route. Supported methods: POST.' error and I can't seem to figure out why.
here is my Authenticate.php
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
here are the routes I have set up
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'Auth\AuthController#login')->name('login');
Route::post('register', 'Auth\AuthController#register');
Route::group([
'middleware' => 'auth:api'
], function () {
Route::get('logout', 'Auth\AuthController#logout');
Route::get('user', 'Auth\AuthController#user');
});
});
Route::get('check', function () {
return response()->json([
'message' => 'YOU'RE IN!'
], 200);
})->middleware('auth:api');
and here is my authController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
//
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'user' => Auth::user(),
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
], 200);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'fName' => 'required|string',
'lName' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string'
]);
if ($validator->fails()) {
$error = $validator->errors()->first();
return response()->json([
'message' => $error
], 404);
}
$user = new User;
$user->first_name = $request->fName;
$user->last_name = $request->lName;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
], 200);
// Auth::logout();
}
public function user(Request $request)
{
return response()->json($request->user());
}
}
when I send my request with a header containing the token it works and I get the "YOU'RE IN" message, when I don't I get the error. I did try to send it as both a POST and a GET request which in fact shouldn't be needed since I have it declared as a GET route.
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The GET method is not supported for this route. Supported methods: POST. in file D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php on line 117
#0 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php(103): Illuminate\Routing\AbstractRouteCollection->methodNotAllowed(Array, 'GET')
#1 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php(40): Illuminate\Routing\AbstractRouteCollection->getRouteForMethods(Object(Illuminate\Http\Request), Array)
#2 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php(162): Illuminate\Routing\AbstractRouteCollection->handleMatchedRoute(Object(Illuminate\Http\Request), NULL)
#3 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\Router.php(639): Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))
#4 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\Router.php(628): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request))
#5 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\Router.php(617): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#6 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(165): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#7 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#8 D:\My Workspace\Laravel\awiz\app\Http\Middleware\Cors.php(18): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#9 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): App\Http\Middleware\Cors->handle(Object(Illuminate\Http\Request), Object(Closure))
#10 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#11 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#12 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#13 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#14 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#15 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#16 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php(63): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#17 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#18 D:\My Workspace\Laravel\awiz\vendor\fruitcake\laravel-cors\src\HandleCors.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#19 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Fruitcake\Cors\HandleCors->handle(Object(Illuminate\Http\Request), Object(Closure))
#20 D:\My Workspace\Laravel\awiz\vendor\fideloper\proxy\src\TrustProxies.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#21 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#22 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#23 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(140): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#24 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(109): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#25 D:\My Workspace\Laravel\awiz\public\index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#26 D:\My Workspace\Laravel\awiz\server.php(21): require_once('D:\\My Workspace...')
#27 {main}
EDIT
I did, in fact, try to change the route the middleware is supposed to redirect me to which in turn caused me to face another error... It says the route isn't defined but am pretty sure it is...
Route::get('loginfailed', function () {
return response()->json(['error' => 'unauthenticated']);
});
this is my route definition and this is the new redirectTo function
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('loginfailed');
}
}
this is the error I get now
Symfony\Component\Routing\Exception\RouteNotFoundException: Route [loginfailed] not defined. in file D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 420
#0 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php(768): Illuminate\Routing\UrlGenerator->route('loginfailed', Array, true)
#1 D:\My Workspace\Laravel\awiz\app\Http\Middleware\Authenticate.php(18): route('loginfailed')
You're getting that error because your middleware is supposed to redirect to login route i.e return route('login');
The problem is that your login route is POST i.e Route::post('login', 'Auth\AuthController#login')->name('login');
if you are using postman to do request to your api make sure you add in Headers (Accept - appication/json) so it will show the Unauthenticated message otherwise it will try to redirect if it doesn't expect json

ZF2 ServiceManager is unable to create doctrine.entitymanager.orm_default

I get the following error, when I try to use doctrine 2 in ZF2.
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.entitymanager.orm_default
The needed modules are included and activated.
doctrine.config.local.php
return [
'doctrine' => [
'connection' => [
'orm_default' => [
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => [
'host' => 'localhost',
'port' => '3306',
'user' => 'root',
'password' => 'password',
'dbname' => 'database',
'charset' => 'utf8',
'driverOptions' => [
1002 => 'SET NAMES utf8'
],
],
],
],
'configuration' => [
'orm_default' => [
'metadata_cache' => 'array',
'query_cache' => 'array',
'result_cache' => 'array',
'hydration_cache' => 'array',
'generate_proxies' => false,
]
]
]
];
module.config.php of Core module (/module/Core/config/module.config.php)
namespace Core;
return [
'service_manager' => include __DIR__ . '/service-manager.config.php',
'router' => include __DIR__ . '/router.config.php',
'view_manager' => include __DIR__ . '/view-manager.config.php',
'translator' => include __DIR__ . '/translator.config.php',
'hydrators' => include __DIR__ . '/hydrators.config.php'
];
doctrine.config.php of Core module (/module/Core/config/doctrine.config.php)
return [
'driver' => [
__NAMESPACE__ . '_driver' => [
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => [
__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity',
]
],
'orm_default' => [
'drivers' => [
__NAMESPACE__ => __NAMESPACE__ . '_driver'
]
]
]
];
Factory
namespace Event\Form\Fieldset\Factory;
use Event\Entity\Event;
use Event\Form\Fieldset\EventFieldset;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class EventFieldsetFactory implements FactoryInterface {
public function createService(ServiceLocatorInterface $formElementManager) {
$serviceLocator = $formElementManager->getServiceLocator();
$hydratorManager = $serviceLocator->get('HydratorManager');
// Here I get the error!
$objectManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
$fieldset = new EventFieldset();
$fieldset->setObjectManager($objectManager);
$fieldset->setHydrator($hydratorManager->get('Core\Hydrator\Doctrine'));
$fieldset->setObject(new Event());
return $fieldset;
}
}
modules in application.config.php
'modules' => [
'DoctrineModule',
'DoctrineORMModule',
'Core',
'Event',
'Inquiry'
]
Stack trace
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
/src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:555
Message:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.entitymanager.orm_default
Stack trace:
#0 /src/vendor/doctrine/doctrine-orm-module/src/DoctrineORMModule/Service/EntityManagerAliasCompatFactory.php(44): Zend\ServiceManager\ServiceManager->get('doctrine.entity...')
#1 [internal function]: DoctrineORMModule\Service\EntityManagerAliasCompatFactory->createService(Object(Zend\ServiceManager\ServiceManager), 'doctrineormenti...', 'Doctrine\ORM\En...')
#2 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(934): call_user_func(Array, Object(Zend\ServiceManager\ServiceManager), 'doctrineormenti...', 'Doctrine\ORM\En...')
#3 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(1092): Zend\ServiceManager\ServiceManager->createServiceViaCallback(Array, 'doctrineormenti...', 'Doctrine\ORM\En...')
#4 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(634): Zend\ServiceManager\ServiceManager->createFromFactory('doctrineormenti...', 'Doctrine\ORM\En...')
#5 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Doctrine\ORM\En...', 'doctrineormenti...')
#6 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#7 /src/module/Event/src/Event/Form/Fieldset/Factory/EventFieldsetFactory.php(22): Zend\ServiceManager\ServiceManager->get('Doctrine\ORM\En...')
#8 [internal function]: Event\Form\Fieldset\Factory\EventFieldsetFactory->createService(Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill), 'eventfieldsetev...', 'Event\Fieldset\...')
#9 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(934): call_user_func(Array, Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill), 'eventfieldsetev...', 'Event\Fieldset\...')
#10 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(330): Zend\ServiceManager\ServiceManager->createServiceViaCallback(Array, 'eventfieldsetev...', 'Event\Fieldset\...')
#11 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(287): Zend\ServiceManager\AbstractPluginManager->createServiceViaCallback(Array, 'eventfieldsetev...', 'Event\Fieldset\...')
#12 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(634): Zend\ServiceManager\AbstractPluginManager->createFromFactory('eventfieldsetev...', 'Event\Fieldset\...')
#13 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Event\Fieldset\...', 'eventfieldsetev...')
#14 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#15 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(161): Zend\ServiceManager\ServiceManager->get('Event\Fieldset\...', true)
#16 /src/vendor/zendframework/zend-form/src/FormElementManager/FormElementManagerTrait.php(38): Zend\ServiceManager\AbstractPluginManager->get('Event\Fieldset\...', Array, true)
#17 /src/vendor/zendframework/zend-form/src/Factory.php(111): Zend\Form\FormElementManager\FormElementManagerV2Polyfill->get('Event\Fieldset\...')
#18 /src/vendor/zendframework/zend-form/src/Form.php(176): Zend\Form\Factory->create(Array)
#19 /src/module/Inquiry/src/Inquiry/Form/InquiryForm.php(19): Zend\Form\Form->add(Array)
#20 /src/vendor/zendframework/zend-form/src/FormElementManager/FormElementManagerV2Polyfill.php(217): Inquiry\Form\InquiryForm->init()
#21 [internal function]: Zend\Form\FormElementManager\FormElementManagerV2Polyfill->callElementInit(Object(Inquiry\Form\InquiryForm), Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill))
#22 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(664): call_user_func(Array, Object(Inquiry\Form\InquiryForm), Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill))
#23 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Inquiry\Form\In...', 'inquiryforminqu...')
#24 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#25 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(161): Zend\ServiceManager\ServiceManager->get('Inquiry\Form\In...', true)
#26 /src/vendor/zendframework/zend-form/src/FormElementManager/FormElementManagerTrait.php(38): Zend\ServiceManager\AbstractPluginManager->get('Inquiry\Form\In...', Array, true)
#27 /src/module/Inquiry/src/Inquiry/Controller/Factory/InquiryControllerFactory.php(23): Zend\Form\FormElementManager\FormElementManagerV2Polyfill->get('Inquiry\Form\In...')
#28 [internal function]: Inquiry\Controller\Factory\InquiryControllerFactory->createService(Object(Zend\Mvc\Controller\ControllerManager), 'inquirycontroll...', 'Inquiry\Control...')
#29 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(934): call_user_func(Array, Object(Zend\Mvc\Controller\ControllerManager), 'inquirycontroll...', 'Inquiry\Control...')
#30 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(330): Zend\ServiceManager\ServiceManager->createServiceViaCallback(Array, 'inquirycontroll...', 'Inquiry\Control...')
#31 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(287): Zend\ServiceManager\AbstractPluginManager->createServiceViaCallback(Array, 'inquirycontroll...', 'Inquiry\Control...')
#32 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(634): Zend\ServiceManager\AbstractPluginManager->createFromFactory('inquirycontroll...', 'Inquiry\Control...')
#33 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Inquiry\Control...', 'inquirycontroll...')
#34 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#35 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(161): Zend\ServiceManager\ServiceManager->get('Inquiry\Control...', true)
#36 /src/vendor/zendframework/zend-mvc/src/DispatchListener.php(94): Zend\ServiceManager\AbstractPluginManager->get('Inquiry\Control...')
#37 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#38 /src/vendor/zendframework/zend-eventmanager/src/EventManager.php(490): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#39 /src/vendor/zendframework/zend-eventmanager/src/EventManager.php(263): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#40 /src/vendor/zendframework/zend-mvc/src/Application.php(340): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#41 /src/public/index.php(15): Zend\Mvc\Application->run()
#42 {main}
First trouble is your config loader. You've modified it to contain:
'config_glob_paths' => [
'config/autoload/local/{,*.}local.php',
'config/autoload/global/{,*.}global.php'
],
But your folders are set as:
config/autoload/global/doctrine.php
So the loaders won't match.
This glob path would work for your file structure:
'config_glob_paths' => [
'config/autoload/local/{,*.}php',
'config/autoload/global/{,*.}php'
],
As alternative, I've uploaded a more 'standard' config setup that could help you:
https://github.com/Saeven/doctrine-error/tree/master/src/config
In short though, you were getting bad errors, because no connection could be established, simply because your DB details were absent (because your config loader was hosed).
Second, looks like your composer.json is loading in some incompatible items. I used one from a project I maintain and combined with the loader fix, I see "test" when I put valid DB creds:
composer.json
{
"name": "test",
"minimum-stability": "dev",
"require": {
"php": ">=5.3.3",
"zendframework/zend-servicemanager": "#stable",
"zendframework/zend-eventmanager": "#stable",
"zendframework/zend-modulemanager": "#stable",
"zendframework/zend-developer-tools": "#stable",
"zendframework/zend-config": "#stable",
"zendframework/zend-console": "#stable",
"zendframework/zend-test": "#stable",
"zendframework/zend-crypt": "#stable",
"zendframework/zend-mail": "#stable",
"zendframework/zend-text": "#stable",
"zendframework/zend-serializer": "#stable",
"zendframework/zend-mvc": "2.5.3",
"zendframework/zend-filter": "#stable",
"zendframework/zend-db": "#stable",
"zendframework/zend-stdlib": "#stable",
"zendframework/zend-view": "#stable",
"zendframework/zend-form": "#stable",
"zendframework/zend-validator": "#stable",
"zendframework/zend-i18n": "#stable",
"zendframework/zend-log": "#stable",
"zendframework/zend-cache": "#stable",
"doctrine/doctrine-orm-module": "0.8.0",
"doctrine/orm": "2.5.*#dev"
}
}
I think your problem is in your factory and how you get the EntityManager.
Here is how to get Doctrine\ORM\EntityManager from serviceLocator in a ZF2 factory :
class YourFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
/* #var $em \Doctrine\ORM\EntityManager */
$em = $serviceLocator->getServiceLocator()->get('em');
// $em contains methods to get repo, etc ...
// injections here
$obj = new Obj();
$obj->setEntityManager($em);
return $obj;
}
}
Try that and let me know

yii\base\InvalidParamException with message The view file does not exist

I'm very new to Yii framework.
I did only basic compulsory steps in setting up advance Yii. But it gives the following error when I try load the index.php(localhost:8888/new/advanced/frontend/web/index.php) in frontend as well as the index.php (localhost:8888/new/advanced/backend/web/index.php) in the backend.
Things I have done from the beginning:
Downloaded the advanced Yii framework & extracted it to the htdocs
Run the command php init in the terminal.that's all...
I tried this solution yii2-error-the-view-file-does-not-exist.. but it didn't worked
Error
An Error occurred while handling another error:
exception 'yii\base\InvalidParamException' with message 'The view file does not exist: /Applications/MAMP/htdocs/SMS_Messenger/vendor/yiisoft/yii2/views/errorHandler/exception.php' in /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/View.php:226
Stack trace:
#0 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/ErrorHandler.php(241): yii\base\View->renderFile('#yii/views/erro...', Array, Object(yii\web\ErrorHandler))
#1 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/ErrorHandler.php(112): yii\web\ErrorHandler->renderFile('#yii/views/erro...', Array)
#2 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/ErrorHandler.php(109): yii\web\ErrorHandler->renderException(Object(yii\base\InvalidParamException))
#3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\base\InvalidParamException))
#4 {main}
Previous exception:
exception 'yii\base\InvalidParamException' with message 'The file or directory to be published does not exist: /Applications/MAMP/htdocs/SMS_Messenger/vendor/yiisoft/yii2/assets' in /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetManager.php:452
Stack trace:
#0 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetBundle.php(179): yii\web\AssetManager->publish('/Applications/M...', Array)
#1 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetManager.php(266): yii\web\AssetBundle->publish(Object(yii\web\AssetManager))
#2 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetManager.php(237): yii\web\AssetManager->loadBundle('yii\\web\\YiiAsse...', Array, true)
#3 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/View.php(284): yii\web\AssetManager->getBundle('yii\\web\\YiiAsse...')
#4 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/View.php(289): yii\web\View->registerAssetBundle('yii\\web\\YiiAsse...', NULL)
#5 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetBundle.php(123): yii\web\View->registerAssetBundle('frontend\\assets...')
#6 /Applications/MAMP/htdocs/new/advanced/frontend/views/layouts/main.php(13): yii\web\AssetBundle::register(Object(yii\web\View))
#7 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/View.php(325): require('/Applications/M...')
#8 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/View.php(247): yii\base\View->renderPhpFile('/Applications/M...', Array)
#9 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Controller.php(392): yii\base\View->renderFile('/Applications/M...', Array, Object(frontend\controllers\SiteController))
#10 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Controller.php(378): yii\base\Controller->renderContent('<div class="sit...')
#11 /Applications/MAMP/htdocs/new/advanced/frontend/controllers/SiteController.php(75): yii\base\Controller->render('index')
#12 [internal function]: frontend\controllers\SiteController->actionIndex()
#13 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/InlineAction.php(55): call_user_func_array(Array, Array)
#14 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Controller.php(154): yii\base\InlineAction->runWithParams(Array)
#15 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Module.php(454): yii\base\Controller->runAction('', Array)
#16 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/Application.php(84): yii\base\Module->runAction('', Array)
#17 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#18 /Applications/MAMP/htdocs/new/advanced/frontend/web/index.php(18): yii\base\Application->run()
#19 {main}
frontend sitecontroller.php
<?php
namespace frontend\controllers;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
//other codes
My environment is Mac OS 10.11 El capitain
since I'm very newbie to Yii & I haven't changed the default code its hard to figure out the problem.
Hope for any suggestion
You don't have vendor directory.
Run composer from command line. Probably you must first install composer. Then in root dir of advanced project run:
composer install
or
php composer install

ZfcUser redirect dynamic url after login

I'm learning to develop a website with ZF2. I have downloaded 2 modules ZfcUser and BjyAuthorize.
The configurations was fairly straight forward after i read the documentations. How ever i did not find any solution for the following situation:
Guest lands on a blog post (www.yourdomain.com/blog/541) ->
BjyAuthorize will redirect guest to the login page -> after successful
login redirect to www.yourdomian.com/blog/541
I have a solution for the redirection when a guest arriving for a restricted area:
public function onBootstrap(MvcEvent $e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$app->getEventManager()->attach(
'route',
function($e) {
$app = $e->getApplication();
$routeMatch = $e->getRouteMatch();
$sm = $app->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');
if (!$auth->hasIdentity() && $routeMatch->getMatchedRouteName() != 'user/login'
&& $routeMatch->getMatchedRouteName() != 'zfcuser/login') {
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine(
'Location',
$e->getRouter()->assemble(
array(),
array('name' => 'zfcuser/login')
)
);
$response->setStatusCode(302);
return $response;
}
},
-100
);
}
But i don't know how should i extend this to solve the above explained action.
Any help is greatly appreciated.
UPDATE
My route:
'blog' => array(
'type' => 'Segment',
'options' => array(
'route' => '/blog/:id',
'constraints' => array (
'id' => '[0-9]+'
),
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'view',
),
),
),
This is my Zfcuser config:
return array(
'zfcuser' => array(
'password_cost' => 4,
'login_after_registration' => true,
'use_redirect_parameter_if_present' => true,
'enable_display_name' => true
)
);
After your updated code i see it should be worked this is what happening with the URL:
http://localhost:10088/BlogProject/user/login?redirect=/BlogProject/blog/1
But when i try to login i received this error:
Route with name "" not found
UPDATE 2
Zend\Mvc\Router\Exception\RuntimeException
File:
/usr/local/zend/var/apps/http/__default__/0/ProjectManager/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Router/Http/TreeRouteStack.php:317
Message:
Route with name "" not found
Stack trace:
#0 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/Plugin/Url.php(99): Zend\Mvc\Router\Http\TreeRouteStack->assemble(Array, Array)
#1 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/Plugin/Redirect.php(48): Zend\Mvc\Controller\Plugin\Url->fromRoute('/BlogProject...', Array, Array, false)
#2 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zf-commons/zfc-user/src/ZfcUser/Controller/UserController.php(158): Zend\Mvc\Controller\Plugin\Redirect->toRoute('/BlogProject...')
#3 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php(83): ZfcUser\Controller\UserController->authenticateAction()
#4 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#5 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#6 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#7 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php(117): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#8 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/Plugin/Forward.php(138): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#9 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zf-commons/zfc-user/src/ZfcUser/Controller/UserController.php(106): Zend\Mvc\Controller\Plugin\Forward->dispatch('zfcuser', Array)
#10 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php(83): ZfcUser\Controller\UserController->loginAction()
#11 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#12 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#13 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#14 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php(117): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#15 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/DispatchListener.php(114): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#16 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#17 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#18 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#19 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php(313): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#20 /usr/local/zend/var/apps/http/__default__/0/BlogProject/1.0.0_46/public/index.php(12): Zend\Mvc\Application->run()
#21 {main}
This is my viewAction:
public function viewAction()
{
$flashMsg = $this->flashMessenger();
if($flashMsg->hasMessages()){
$variables['success'] = $flashMsg->getMessages()[0];
$flashMsg->clearMessages();
}
$variables['blogs'] = $this->mapper->getAllMyBlogs($this->zfcUserAuthentication()->getIdentity()->getId());
$variables['contributedBlogs'] = $this->mapper->getAllMyContributedBlogs($this->zfcUserAuthentication()->getIdentity()->getId());
$variables['activeBlog'] = $this->getEvent()->getRouteMatch()->getParam('id');
$this->vm->setVariables($variables);
$this->vm->setTemplate('application/index/index.phtml');
return $this->vm;
}
SOLUTION
I've found the solution:
if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
return $this->redirect()->toRoute($redirect);
}
This one is has to be changed:
if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
return $this->redirect()->toUrl($redirect);
}
And your code will work totally fine.
You can find it in UserController line 157.
You can take advantage of the use_redirect_parameter_if_present option implemented in ZfcUser. If it's set to true (which is by default), and you add a redirect parameter to the login route, it will automatically redirects you to this route once you're logged. Your function could be:
$eventManager->attach( MvcEvent::EVENT_ROUTE, function( $e ) use ( $serviceManager ) {
$routeMatch = $e->getRouteMatch();
$auth = $serviceManager->get('zfcuser_auth_service');
if (!$auth->hasIdentity() && $routeMatch->getMatchedRouteName() != 'user/login'
&& $routeMatch->getMatchedRouteName() != 'zfcuser/login') {
//GENERATE THE URL FROM CURRENT ROUTE (YOUR blog ONE)
$redirect = $e->getRouter()->assemble(
$routeMatch->getParams(),
array(
'name' => $routeMatch->getMatchedRouteName(),
)
);
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine(
'Location',
$e->getRouter()->assemble(
array(),
array(
'name' => 'zfcuser/login',
'query' => array( 'redirect' => $redirect )
)
)
);
$response->setStatusCode(302);
return $response;
}
} );
Although, seems been long, I was able to fix this by just replacing the RedirectCallBack class. It was having problem here on two of these functions
private function routeExists($route)
{
try {
$this->router->assemble(array(), array('name' => $route));
} catch (Exception\RuntimeException $e) {
return false;
}
return true;
}
protected function getRedirect($currentRoute, $redirect = false)
{
$useRedirect = $this->options->getUseRedirectParameterIfPresent();
$routeExists = ($redirect && $this->routeExists($redirect));
if (!$useRedirect || !$routeExists) {
$redirect = false;
}
switch ($currentRoute) {
case 'zfcuser/register':
case 'zfcuser/login':
case 'zfcuser/authenticate':
$route = ($redirect) ?: $this->options->getLoginRedirectRoute();
return $this->router->assemble(array(), array('name' => $route));
break;
case 'zfcuser/logout':
$route = ($redirect) ?: $this->options->getLogoutRedirectRoute();
return $this->router->assemble(array(), array('name' => $route));
break;
default:
return $this->router->assemble(array(), array('name' => 'zfcuser'));
}
}
See here for the solved code
It should be
private function routeExists($route)
{
// first check if such rout/name exists
// will throw exception if does not exist
$namedRouteMatch=0;
$urlRouteMatch=0;
try{
$this->router->assemble(array(), array('name' => $route));
}catch (Exception\RuntimeException $e) {
// didnt' match with any route name
$match=0;
}
// now try to match url with routes
try {
$request=$this->application->getRequest();
$request->setUri($route);
$matchedRoute = $this->router->match($request);
if($matchedRoute){
$urlRouteMatch=1;
}
} catch (Exception\RuntimeException $e) {
$urlRouteMatch=0;
}
// check if anyof them matched
if($namedRouteMatch || $urlRouteMatch){
return true;
}
}
protected function getRedirect($currentRoute, $redirect = false)
{
$useRedirect = $this->options->getUseRedirectParameterIfPresent();
$routeExists = ($redirect && $this->routeExists($redirect));
if (!$useRedirect || !$routeExists) {
$redirect = false;
}
switch ($currentRoute) {
case 'zfcuser/register':
case 'zfcuser/login':
case 'zfcuser/authenticate':
if($redirect){
return $redirect;
}
$route =$this->options->getLoginRedirectRoute();
return $this->router->assemble(array(), array('name' => $route));
break;
case 'zfcuser/logout':
$route = ($redirect) ?: $this->options->getLogoutRedirectRoute();
return $this->router->assemble(array(), array('name' => $route));
break;
default:
return $this->router->assemble(array(), array('name' => 'zfcuser'));
}
}

Categories