My app is built on the 'advanced' Yii2 application template and my User class is built on the Yii2-user module.
The app seems to use the custom User model class dektrium\user\Module to handle registration as the custom fields I've added are being stored in the database on signup, using the register() method of the vendor User class to do the database persistence operations.
When I access the account settings page, using the action /user/settings/account the model class being used to display the User data is actually common/model/User, as shown by using get_class() and I can't use any of the new methods defined in the custom model class.
Main config file.
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=DBNAME',
'username' => 'DBUSER',
'password' => 'DBPASS',
'charset' => 'utf8',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
],
],
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
'rbac' => [
'class' => 'dektrium\rbac\Module'
],
],
];
And the SettingsForm class which has a User as a property.
<?php
/*
* This file is part of the Dektrium project.
*
* (c) Dektrium project <http://github.com/dektrium/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace dektrium\user\models;
use dektrium\user\helpers\Password;
use dektrium\user\Mailer;
use dektrium\user\Module;
use yii\base\Model;
use yii\base\NotSupportedException;
/**
* SettingsForm gets user's username, email and password and changes them.
*
* #property User $user
*
* #author Dmitry Erofeev <dmeroff#gmail.com>
*/
class SettingsForm extends Model
{
/** #var string */
public $email;
/** #var string */
// public $username;
/** #var string */
public $new_password;
/** #var string */
public $current_password;
/** #var Module */
protected $module;
/** #var Mailer */
protected $mailer;
/** #var User */
private $_user;
/** #return User */
public function getUser()
{
if ($this->_user == null) {
$this->_user = \Yii::$app->user->identity;
}
return $this->_user;
}
/** #inheritdoc */
public function __construct(Mailer $mailer, $config = [])
{
$this->mailer = $mailer;
$this->module = \Yii::$app->getModule('user');
$this->setAttributes([
//'username' => $this->user->username,
'email' => $this->user->unconfirmed_email ?: $this->user->email
], false);
parent::__construct($config);
}
/** #inheritdoc */
public function rules()
{
return [
// 'usernameRequired' => ['username', 'required'],
// 'usernameTrim' => ['username', 'filter', 'filter' => 'trim'],
// 'usernameLenth' => ['username', 'string', 'min' => 3, 'max' => 20],
// 'usernamePattern' => ['username', 'match', 'pattern' => '/^[-a-zA-Z0-9_\.#]+$/'],
'emailRequired' => ['email', 'required'],
'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
'emailPattern' => ['email', 'email'],
// 'emailUsernameUnique' => [['email', 'username'], 'unique', 'when' => function ($model, $attribute) {
// return $this->user->$attribute != $model->$attribute;
// }, 'targetClass' => $this->module->modelMap['User']],
'newPasswordLength' => ['new_password', 'string', 'min' => 6],
'currentPasswordRequired' => ['current_password', 'required'],
'currentPasswordValidate' => ['current_password', function ($attr) {
if (!Password::validate($this->$attr, $this->user->password_hash)) {
$this->addError($attr, \Yii::t('user', 'Current password is not valid'));
}
}]
];
}
/** #inheritdoc */
public function attributeLabels()
{
return [
'email' => \Yii::t('user', 'Email'),
'username' => \Yii::t('user', 'Username'),
'new_password' => \Yii::t('user', 'New password'),
'current_password' => \Yii::t('user', 'Current password')
];
}
/** #inheritdoc */
public function formName()
{
return 'settings-form';
}
/**
* Saves new account settings.
*
* #return bool
*/
public function save()
{
if ($this->validate()) {
// $this->user->scenario = 'settings';
// $this->user->username = $this->username;
$this->user->password = $this->new_password;
if ($this->email == $this->user->email && $this->user->unconfirmed_email != null) {
$this->user->unconfirmed_email = null;
} else if ($this->email != $this->user->email) {
switch ($this->module->emailChangeStrategy) {
case Module::STRATEGY_INSECURE:
$this->insecureEmailChange(); break;
case Module::STRATEGY_DEFAULT:
$this->defaultEmailChange(); break;
case Module::STRATEGY_SECURE:
$this->secureEmailChange(); break;
default:
throw new \OutOfBoundsException('Invalid email changing strategy');
}
}
return $this->user->save();
}
return false;
}
/**
* Changes user's email address to given without any confirmation.
*/
protected function insecureEmailChange()
{
$this->user->email = $this->email;
\Yii::$app->session->setFlash('success', \Yii::t('user', 'Your email address has been changed'));
}
/**
* Sends a confirmation message to user's email address with link to confirm changing of email.
*/
protected function defaultEmailChange()
{
$this->user->unconfirmed_email = $this->email;
/** #var Token $token */
$token = \Yii::createObject([
'class' => Token::className(),
'user_id' => $this->user->id,
'type' => Token::TYPE_CONFIRM_NEW_EMAIL
]);
$token->save(false);
$this->mailer->sendReconfirmationMessage($this->user, $token);
\Yii::$app->session->setFlash('info', \Yii::t('user', 'A confirmation message has been sent to your new email address'));
}
/**
* Sends a confirmation message to both old and new email addresses with link to confirm changing of email.
* #throws \yii\base\InvalidConfigException
*/
protected function secureEmailChange()
{
$this->defaultEmailChange();
/** #var Token $token */
$token = \Yii::createObject([
'class' => Token::className(),
'user_id' => $this->user->id,
'type' => Token::TYPE_CONFIRM_OLD_EMAIL
]);
$token->save(false);
$this->mailer->sendReconfirmationMessage($this->user, $token);
// unset flags if they exist
$this->user->flags &= ~User::NEW_EMAIL_CONFIRMED;
$this->user->flags &= ~User::OLD_EMAIL_CONFIRMED;
$this->user->save(false);
\Yii::$app->session->setFlash('info', \Yii::t('user', 'We have sent confirmation links to both old and new email addresses. You must click both links to complete your request'));
}
}
The module property is showing the type to be the custom User but the _user is from the /common/models/User.
Have I missed something to say that any User objects should be of the custom class, so I can access the new properties/methods?
At the moment I have changed the common/models/User class to simply extend the User in dektrium/user/models/User with no actual code in the common User class.
class User extends \dektrium\user\models\User {}
It has solved my problem for now, but it feels like a really bad solution. Any further input would be gratefully received...
Edit:
I'd forgotten about this Q&A...
in my common/config/main.php where the user module is declared, in the modelMap I'm able to specify to use my own custom User model, something like the following.
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
'modelMap' => [
'User' => 'common\models\User',
],
Where there is an entry for each model used by the dektrium user module.
Related
I have two tables. One for Users, one for Equipments.
I managed to make the search for username from other table, but now i want to create an equipment or to update an equipment directly to username, not by user_for_id. Is there any posibilty to do that ? Which would be the steps ? Thank you very much for any guidance.
First table : user_id - primary key, username, password ;
Second table: user_equip_id - primary key, phone_model, phone_model_series, phone_date_acq, nb_sg_model, nb_sg,_date_acq, display_model, display_series, display_date_acq, user_for_id - foreign key to user_id from table1
Controller:
<?php
namespace app\controllers;
use Yii;
use app\models\Equipment;
use app\models\EquipmentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
* EquipmentController implements the CRUD actions for Equipment model.
*/
class EquipmentController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
/**
* Lists all Equipment models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new EquipmentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Equipment model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Equipment model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Equipment();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->user_equip_id]);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Equipment model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->user_equip_id]);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Equipment model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Equipment model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Equipment the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Equipment::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "equipment".
*
* #property int $user_equip_id
* #property string|null $phone_model
* #property string $phone_series
* #property string $phone_date_acq
* #property string $nb_sg_model
* #property string $nb_sg_series
* #property string $nb_sg_date_acq
* #property string $display_model
* #property string $display_series
* #property string $display_date_acq
* #property int $user_for_id
*
* #property User $userFor
*/
class Equipment extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'equipment';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['phone_series', 'phone_date_acq', 'nb_sg_model', 'nb_sg_series', 'nb_sg_date_acq', 'display_model', 'display_series', 'display_date_acq', 'user_for_id'], 'required'],
[['phone_date_acq', 'nb_sg_date_acq', 'display_date_acq'], 'safe'],
[['user_for_id'], 'integer'],
[['userFor'], 'safe'],
[['phone_model', 'phone_series', 'nb_sg_model', 'nb_sg_series', 'display_model', 'display_series'], 'string', 'max' => 50],
[['user_for_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_for_id' => 'user_id']],
[['userFor'], 'string', 'max' => 50],
//[['username'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['username' => 'username']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'user_equip_id' => 'User Equip ID',
'phone_model' => 'Phone Model',
'phone_series' => 'Phone Series',
'phone_date_acq' => 'Phone Date',
'nb_sg_model' => 'NB/GS Model',
'nb_sg_series' => 'NB/GS Series',
'nb_sg_date_acq' => 'NB/GS Date',
'display_model' => 'Display Model',
'display_series' => 'Display Series',
'display_date_acq' => 'Display Date',
'user_for_id' => 'User For ID',
'userFor.username' => 'Username',
];
}
/**
* Gets query for [[UserFor]].
*
* #return \yii\db\ActiveQuery|yii\db\ActiveQuery
*/
public function getUserFor()
{
return $this->hasOne(User::className(), ['user_id' => 'user_for_id']);
}
//public function getUsername()
//{
// print_r($equipment->userFor->username);die;
// }
/**
* {#inheritdoc}
* #return EquipmentQuery the active query used by this AR class.
*/
public static function find()
{
return new EquipmentQuery(get_called_class());
}
}
Model Search:
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Equipment;
/**
* EquipmentSearch represents the model behind the search form of `app\models\Equipment`.
*/
class EquipmentSearch extends Equipment
{
public $userFor;
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_equip_id', 'user_for_id'], 'integer'],
[['phone_model', 'phone_series', 'phone_date_acq', 'nb_sg_model', 'nb_sg_series', 'nb_sg_date_acq', 'display_model', 'display_series', 'display_date_acq'], 'safe'],
[['userFor'], 'safe'],
#[['username'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Equipment::find();
$query->joinWith(['userFor']);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['username'] = [
'asc' => ['user.username' => SORT_ASC],
'desc' => ['user.username' => SORT_DESC],
];
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'user_equip_id' => $this->user_equip_id,
'phone_date_acq' => $this->phone_date_acq,
'nb_sg_date_acq' => $this->nb_sg_date_acq,
'display_date_acq' => $this->display_date_acq,
'user_for_id' => $this->user_for_id,
]);
$query->andFilterWhere(['like', 'phone_model', $this->phone_model])
->andFilterWhere(['like', 'phone_series', $this->phone_series])
->andFilterWhere(['like', 'nb_sg_model', $this->nb_sg_model])
->andFilterWhere(['like', 'nb_sg_series', $this->nb_sg_series])
->andFilterWhere(['like', 'display_model', $this->display_model])
->andFilterWhere(['like', 'display_series', $this->display_series])
->andFilterWhere(['like', 'user.username', $this->userFor]);
return $dataProvider;
}
}
Thank you in advance for any guidance or help.
I'm creating a custom login controller using a custom auth guard named 'students' but when logging in auth guard attempt always return false.
class login extends Controller
{
use AuthenticatesUsers;
public function index()
{
return view('voters.Auth.login');
}
public function checklogin(Request $request)
{
$this->validate($request, [
'votersid' => 'required',
'passcode' => 'required|alphaNum|min:3'
]);
$studentid = $request->get('votersid');
$pass = $request->get('passcode');
if (Auth::guard('student')->attempt(['Student_ID' => $studentid, 'passcode' => $pass])) {
return redirect('login/success');
}
return back()
->withInput($request->all())
->with('error', 'Please check your Student ID / Passcode.');
}
public function successlogin()
{
if (Auth::guard('student')->check()) {
return view('successlogin');
}
return redirect('/vote/login')
->with('error', 'Please Login first to authenticate.');
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
return redirect('/');
}
}
The configuration is as follows
'guards' => [
'web' => [ 'driver' => 'session', 'provider' => 'users', ],
'student' => [ 'driver' => 'session', 'provider' => 'student', ],
'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => false, ],
],
...
'providers' => [
'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ],
'student' => [ 'driver' => 'eloquent', 'model' => App\Student::class, ],
// 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ],
Student Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Student extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'Student_ID', 'password', 'FirstName', 'LastName', 'MiddleName', 'GradeLvl',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
/**
* Send the email verification notification.
*
* #return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new VerifyEmail);
}
/**
* Get the name of the unique identifier for the user.
*
* #return string
*/
public function getAuthIdentifierName()
{
// TODO: Implement getAuthIdentifierName() method.
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
// TODO: Implement getAuthIdentifier() method.
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
// TODO: Implement getAuthPassword() method.
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken()
{
// TODO: Implement getRememberToken() method.
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
// TODO: Implement setRememberToken() method.
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
// TODO: Implement getRememberTokenName() method.
}
}
expecting to login using the custom auth guard but when i entered then correct credential the guard always return false instead of true or login successfully.
I have problem when making modelsearch in yii2. Here's is relation diagram
I want to display Jurusan from table aitambah to table ais3 and I want to display NamaMahasiswa from table ai to ais3. I made table s3penghubung so that table aitambah can be related to ais3. I was able to display them. But, when I try to type "BIO" in Jurusan field, the searching not working properly. it is refreshing the page. there is no any change to the rows displayed. so, what should I do to fix that?
MODEL SEARCH CODE
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Ais3;
use app\models\AiTambah;
/**
* Ais3Search represents the model behind the search form about `app\models\Ais3`.
*/
class Ais3Search extends Ais3
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'kode'], 'integer'],
[['NRP', 'NRP1', 'NRP2', 'NRP3', 'NRP4', 'NRP5', 'NRP6', 'NRP7', 'namaMahasiswaText', 'ProgramStudi', 'TanggalMasuk', 'TanggalKeluar', 'jURUSANText','NAMKANTOR','ANGKATAN'], 'safe'],
];
}
public $NamaMahasiswa;
public $namaMahasiswaText;
public $NRP1;
public $NRP2;
public $NRP3;
public $NRP4;
public $NRP5;
public $NRP6;
public $NRP7;
public $JURUSAN;
public $jURUSANText;
public $NAMKANTOR;
public $ANGKATAN;
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Ais3::find();
$query->joinWith('ai');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'kode' => $this->kode,
]);
$query->andFilterWhere(['like', 'ais3.NRP', $this->NRP])
->andFilterWhere(['like', 'ai.NamaMahasiswa', $this->namaMahasiswaText])
->andFilterWhere(['like', 'ais3.ProgramStudi', $this->ProgramStudi])
->andFilterWhere(['like', 'ai.TanggalMasuk', $this->TanggalMasuk])
->andFilterWhere(['like', 'ais3.TanggalKeluar', $this->TanggalKeluar])
->andFilterWhere(['like', 'aitambah.JURUSAN', $this->JURUSAN]);
return $dataProvider;
}
}
MY GRIDVIEW CODE
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'NRP',
'namaMahasiswaText',
'ProgramStudi',
//'TanggalMasuk',
[
'attribute' => 'TanggalMasuk',
'value' => function($data) {
return $data->ai->TanggalMasuk;
},],
'TanggalKeluar',
//YANG DITAMBAH
/*[
'attribute'=>'NRP1',
'value'=>'s3penghubung.aitambah.JURUSAN',
'label' => 'Jurusan',
],*/
'jURUSANText',
[
'attribute'=>'NRP2',
'value'=>'s3penghubung.aitambah.NAMKANTOR',
'label' => 'Nama Kantor',
],
[
'attribute'=>'NRP3',
'value'=>'s3penghubung.aitambah.ANGKATAN',
'label' => 'Angkatan',
],
[
'attribute'=>'NRP4',
'value'=>'s3penghubung.aitambah.TELP',
'label' => 'Nomor HP/Telp',
],
[
'attribute'=>'NRP5',
'value'=>'s3penghubung.aitambah.PEKERJAAN',
'label' => 'Pekejaan',
],
[
'attribute'=>'NRP6',
'value'=>'s3penghubung.aitambah.EMAIL',
'label' => 'Email',
],
[
'attribute'=>'NRP7',
'value'=>'s3penghubung.aitambah.KODEPROP',
'label' => 'KodeProp',
],
// 'kode',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
MY MODEL'S CODE
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "ais3".
*
* #property integer $id
* #property string $NRP
* #property string $ProgramStudi
* #property string $TanggalMasuk
* #property string $TanggalKeluar
* #property integer $kode
*
* #property Ai $nRP
* #property S3penghubung $kode0
*/
class Ais3 extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'ais3';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['kode'], 'required'],
[['kode'], 'integer'],
[['NRP'], 'string', 'max' => 15],
[['ProgramStudi'], 'string', 'max' => 5],
[['TanggalMasuk', 'TanggalKeluar'], 'string', 'max' => 20],
[['NRP'], 'exist', 'skipOnError' => true, 'targetClass' => Ai::className(), 'targetAttribute' => ['NRP' => 'NRP']],
[['kode'], 'exist', 'skipOnError' => true, 'targetClass' => S3penghubung::className(), 'targetAttribute' => ['kode' => 'kode']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'NRP' => Yii::t('app', 'Nrp'),
'ProgramStudi' => Yii::t('app', 'Program Studi'),
'TanggalMasuk' => Yii::t('app', 'Tanggal Masuk'),
'TanggalKeluar' => Yii::t('app', 'Tanggal Keluar'),
'kode' => Yii::t('app', 'Kode'),
'namaMahasiswaText' => Yii::t('app', 'Nama Mahasiswa'),
'jURUSANText' => Yii::t('app', 'Jurusan'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getai()
{
return $this->hasOne(Ai::className(), ['NRP' => 'NRP']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getS3penghubung()
{
return $this->hasOne(S3penghubung::className(), ['kode' => 'kode']);
}
//YANG DITAMBAH
public function getRelasiS3()
{
return array(
'aitambah'=>array(self::MANY_MANY, 'Aitambah', 'S3Penghubung(AiS3.id, Aitambah.NRP)'),
);
}
public function getNamaMahasiswaText()
{
$ai = ai::findOne(['NRP'=> $this->NRP]);
if (empty($ai))
return '';
return $ai->NamaMahasiswa;
}
public function getJURUSANText()
{
$aitambah = aitambah::findOne(['NRP'=> $this->NRP]);
if (empty($aitambah))
return '';
return $aitambah->JURUSAN;
}
}
I dont know how to fix those codes. Could you please help me to solve this? Thankyou
Your code is very difficult to debug. Try to keep a consistency for your naming conventions. The Yii way is all lower case letters separated with underscores.
Please read this and this about displaying and sorting relations.
As for the solution you can experiment a bit with the following:
Create a new relation in your model:
/**
* #return \yii\db\ActiveQuery
*/
public function getAitambah()
{
return $this->hasOne(Aitambah::className(), ['NRP' => 'NRP']);
}
Then in your SearchModel:
public function rules()
{
return [
[['id', 'kode'], 'integer'],
[['NRP', 'NRP1', 'NRP2', 'NRP3', 'NRP4', 'NRP5', 'NRP6', 'NRP7', 'namaMahasiswaText', 'ProgramStudi', 'TanggalMasuk', 'TanggalKeluar', 'jURUSANText','NAMKANTOR','ANGKATAN', 'JURUSAN'], 'safe'],
];
}
And in your search method:
...
$query = Ais3::find();
query->joinWith(['ai ai', 'aitambah aitambah']);
...
Finally in your view:
[
'attribute' => 'JURUSAN',
'value' => 'aitambah.JURUSAN',
'label' => 'JURUSAN',
],
When i try to log in , it redirects me to www.example.com/admin/{username} but it shows a NotFoundHttpException error. Thank you in advance!
The routes.php file
Route::get('/admin', 'SessionsController#create');
Route::get('/logout', 'SessionsController#destroy');
Route::get('profile', function()
{
return "welcome! Your username is" . Auth::admin()->username;
});
Route::resource('sessions', 'SessionsController', ['only' => ['index', 'create', 'destroy', 'store']]);
here is the controller SessionsController.php
<?php
class SessionsController extends \BaseController {
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('admins');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator -> passes()){
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if(Auth::admin($credentials,true)){
$username = Input::get('username');
return Redirect::to("admin/{$username}");
} else {
return Redirect::to('/admin')->withErrors('Username or password invalid');
}
} else {
return Redirect::to('/admin')->withErrors($validator->messages());
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
Auth::logout();
return Redirect::home();
}
}
the admins.blade.php
{{Form::open(array('route' => 'sessions.store'))}}
<h1>ADMIN LOGIN </h1>
{{Form::label('username', 'Username')}}
{{Form::text('username')}}
{{Form::label('password', 'Password')}}
{{Form::password('password')}}
{{Form::submit('Login')}}
{{$errors->first()}}
{{Form::close()}}
and here is the model Admin.php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Admin extends Eloquent implements UserInterface, RemindableInterface {
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'admins';
}
I also installed ollieread multiauth
and here is auth.php file
return array(
'multi' => array(
'admin' => array(
'driver' => 'database',
'model' => 'Admin',
'table' => 'admins'
),
'user' => array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users'
)
),
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
You haven't declared any routes pointing to /admin/{username} . That's the reason it can't be found by laravel.
Here is an example:
In your route files
Route::get('/admin/{username}', 'SessionsController#getByUserName');
I strongly advice you to use named routes. They are a lot easier to manage, even if your application gets bigger.
For example
In your route files
Route::get('/admin/{username}',array('as' => 'admin.username', 'uses'=>'SessionsController#getByUserName'));
Then you can call the url that points to the certain controller either using
URL::route('admin.username')(inside views) or
Redirect::route('admin.username') (inside controller)
You can also pass variables using an array. like this
URL::route('admin.username',array($user->username))
More about routing here
I edited the store method , now the problem is that when i try to login it redirect to www.example.com/admin but it shows a NotFoundHttpException.
The routes.php file
Route::get('/admin', 'SessionsController#create');
Route::get('/logout', 'SessionsController#destroy');
Route::get('profile', function()
{
return "welcome! Your username is" . Auth::admin()->username;
});
Route::resource('sessions', 'SessionsController', ['only' => ['index', 'create', 'destroy', 'store']]);
here is the controller SessionsController.php
<?php
class SessionsController extends \BaseController {
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('admins');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator -> passes()){
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if(Auth::admin($credentials,true)){
$username = Input::get('username');
return Redirect::to("admin/{$username}");
} else {
return Redirect::to('/admin')->withErrors('Username or password invalid');
}
} else {
return Redirect::to('/admin')->withErrors($validator->messages());
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
Auth::logout();
return Redirect::home();
}
}
the admins.blade.php
{{Form::open(array('route' => 'sessions.store'))}}
<h1>ADMIN LOGIN </h1>
{{Form::label('username', 'Username')}}
{{Form::text('username')}}
{{Form::label('password', 'Password')}}
{{Form::password('password')}}
{{Form::submit('Login')}}
{{$errors->first()}}
{{Form::close()}}
and here is the model Admin.php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Admin extends Eloquent implements UserInterface, RemindableInterface {
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'admins';
}
I also installed ollieread multiauth
and here is auth.php file
return array(
'multi' => array(
'admin' => array(
'driver' => 'database',
'model' => 'Admin',
'table' => 'admins'
),
'user' => array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users'
)
),
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
In your admin template you set the goto url as sessions.store which hits SessionsController::store in that method you have a debug function dd() which is throwing that string. It get's called because auth::attempt() returns false as by your own code:
if($attempt) return Redirect::intended('/');
So the behavior is exactly doing what it should. If you are succesfully logged in, you are redirected otherwise it will dump through dd()
What you have to do is filter. You have to add custom error message on app/filter.php
Like the following
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('/')->with('message', 'Please login first');
}
}
});
Above code, I redirect to / and gave Please login first message.