I am trying to send email after user successfully register. so right now i am stuck to pass data in email template.I am sending email with Mailable . so from my Register Controller i using like that Mail::to('example#email.com','User Name')->send(new Verify_Email())
So my question is how to pass array param into new Verify_Email()Massage build class.and so then how to pass from Verify_Email to View.
RegisterController.php
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$confirmation_code = str_random(30);
$user = User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => $confirmation_code
]);
$email_data = ([
'name' => $data['firstname'].' '.$data['lastname'],
'link' => '#'
]);
Mail::to('example#email.com','User Name')->send(new Verify_Email());
return $user;
}
Verify_Email.php
class Verify_Email extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->view('emails.verify-user');
//--------------------------> **Send data to view**
//->with([
//'name' => $this->data->name,
//'link' => $this->data->link
//]);
}
Please follow this approach
Pass the inputs to the Verify_Email constructor and use $this->variable to pass them onto the view.
Mail::to('example#email.com','User Name')->send(new Verify_Email($inputs))
and then this in Verify_Email
class Verify_Email extends Mailable {
use Queueable, SerializesModels;
protected $inputs;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($inputs)
{
$this->inputs = $inputs;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->view('emails.verify-user')
->with([
'inputs' => $this->inputs,
]);
}
}
Hope that answers your question :)
Related
Error Message:
Call to undefined method App\User::roles()
I'm Tring to assign default role to new user But I failed to assigned it. All user information stored in database but Role can't stored in table. Where i mistaked in this code. Help me.My English not good, Sorry for miss-communication.
This is My Code of User.php, Role.php, RegisterController.php and HomeController.php Files. See and tell me "where i doing wrong?"
This is User.php File
namespace App;
use App\Role;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* #param string|array $roles
*/
public function authorizeRoles($roles)
{
if (is_array($roles)) {
return $this->hasAnyRole($roles) ||
abort(401, 'This action is unauthorized.');
}
return $this->hasRole($roles) ||
abort(401, 'This action is unauthorized.');
}
/**
* Check multiple roles
* #param array $roles
*/
public function hasAnyRole($roles)
{
return null !== $this->roles()->whereIn('name', $roles)->first();
}
/**
* Check one role
* #param string $role
*/
public function hasRole($role)
{
return null !== $this->roles()->where('name', $role)->first();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This is Role.php File
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
This RegisterController.php File.
<?php
namespace App\Http\Controllers\Auth;
use App\Role;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user
->roles()
->attach(Role::where('name', 'student')->first());
return $user;
}
This is my role_user database Table
User Database Table
Role Database Table
Refactor your create method in RegisterController.php file like this:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user
->roles()
->attach(Role::where('name', 'student')->first());
return $user;
}
your rest of the code will not run after return.
and add roles relation to User model like this:
public function roles()
{
return $this->belongsToMany(User::class);
}
You can update your create function with this
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role = new App\Role(['role' => 'student']);
$user->roles()->save($role);
return $user;
}
Source: https://laracasts.com/discuss/channels/laravel/attach-role-to-a-user-upon-registration?page=1
You don't currently have a roles() relation in your user model. Add the following
public function roles()
{
return $this->hasMany('App\Role');
}
I am working in Laravel 5.5, and I don't want to write logic in controller, I would like to separate logic form Controller. write something like interface and services like what we user to do in "ASP.NET MVC" frameworks.
I also switched to Laravel coming from Zend and missed my Services. To sooth myself I have implemented a Service namespace which sits in namespace App\Services. In there I do all my Model / Validation handeling. I have experienced no loss of functionality or anything.
<?php
namespace App\Http\Controllers;
use App\Services\Contact as ContactService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
class IndexController extends Controller
{
/**
* Create a new controller instance.
*
* #param Request $request
* #return void
*/
public function __construct(Request $request)
{
$this->_request = $request;
}
/**
* Standard contact page
*
* #return contact page
*/
public function contact(ContactService $contactService)
{
$errors = null;
$success = false;
if ($this->_request->isMethod('post')) {
$validator = $contactService->validator($this->_request->all());
if ($validator->fails()) {
$errors = $validator->errors();
} else {
$contactService->create($validator->getData());
$success = true;
}
}
return view('pages/contact', ['errors' => $errors, 'success' => $success]);
}
}
Example of Service:
<?php
namespace App\Services;
use Validator;
use Mail;
use App\Models\Contact as ContactModel;
class Contact
{
/**
* Get a validator for a contact.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255',
'phone' => 'max:255',
'firstName' => 'required|max:255',
'lastName' => 'required|max:255',
'message' => 'required'
]);
}
/**
* Create a new contact instance after a valid form.
*
* #param array $data
* #return ContactModel
*/
public function create(array $data)
{
$data = [
'email' => $data['email'],
'firstName' => $data['firstName'],
'lastName' => $data['lastName'],
'language' => $data['language'],
'phone' => $data['phone'],
'message' => $data['message']
];
// Send an email
Mail::send('emails.contact', ['data' => $data], function ($m) use ($data) {
$m->from(config('mail.from.address'), config('mail.from.name'));
$m->to(env('MAIL_TO', 'hello#world.com'), env('MAIL_TO'))->subject('Contact form entry from: ' . $data['firstName']);
});
return ContactModel::create($data);
}
}
I would like to send some emails after users registered.
But, it doest work. I didn't receive an email in my SMTP mail. I'm using mailtrap.io.
I have set up a Registered event with a listener to NewUserRegistered.
Within my NewUserRegistered Controller\Auth\AuthController as follows:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Log;
use Validator;
use Mail;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware($this->guestMiddleware(), [
'except' => 'logout'
]);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data) {
return Validator::make($data, [
'name' => 'required|max:255',
'matric' => 'required|max:5',
'faculty' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'address' => 'required',
'phone' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data) {
return User::create([
'name' => $data['name'],
'matric' => $data['matric'],
'faculty' => $data['faculty'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'address' => $data['address'],
'phone' => $data['phone'],
]);
event(new Registered($user));
//sreturn User;
}
}
Within my Registered Events as follows:
<?php
namespace App\Events;
use App\Events\Registered;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class Registered extends Event
{
use SerializesModels;
/**
* #var
*/
public $user;
/**
* Create a new event instance.
*
* #param $user
*/
public function __construct($user)
{
//
$this->user = $user;
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn()
{
return [];
}
}
Within my NewUserRegistered Listeners as follows:
<?php
namespace App\Listeners;
use App\Events\Registered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Mailer;
use Mail;
class NewUserRegistered
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Handle the event.
*
* #param Registered $event
* #return void
*/
public function welcome(Registered $event)
{
$data = [
'user' => $event->user,
'from' => 'hello#test.dev',
'subject' => 'Welcome to test'
];
$this->mailer->send('emails.auth.verify', $data, function($message) {
$message->to($data['user']->email, $data['user']->matric)
->subject($data['subject']);
});
}
}
Your event never fires because you're returning the user after creating them. Your code should have thrown errors when you attempted. Change your code to this.
use App\Events\Registered;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'matric' => $data['matric'],
'faculty' => $data['faculty'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'address' => $data['address'],
'phone' => $data['phone'],
]);
event(new Registered($user));
return $user;
}
Also be sure to register your event listener.
A couple potential issues with your solution could be:
In Controller\Auth\AuthController, you haven't imported the Registered event into the namespace. Try adding use App\Events\Registered; to the top.
In NewUserRegistered, you've defined a #welcome method, but Laravel event listeners expect a #handle method. See the Laravel docs on Events for more information.
Beyond that, you could be experiencing issues with your Mailtrap credentials.
I'm new in StackOverflow and also new using the framework Yii 2, and I need to get session data and put in a create and update form using the _form.php from a view called Planficacion, but when I try to use this line of code in the form:
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::getvalue(Yii::$app->user->identity->rutProfesor,'nombreProfesor')) ?>
Return this error: PHP Warning – yii\base\ErrorException. Invalid argument supplied for foreach()
I need to get the value of 'nombreProfesor' from a model called Profesor, and the relation of both Planificacion and Profesor is 'rutProfesor' and I want to show in the dropDownList only the 'nombreProfesor' of the actual session.
There are the codes from:
Profesor Model (Profesor.php)
<?php
namespace common\models;
use Yii;
class Profesor extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'profesor';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['rutProfesor'], 'required'],
[['nombreProfesor', 'apellidoProfesor', 'escuelaProfesor'], 'string', 'max' => 45],
[['rutProfesor', 'claveProfesor'], 'string', 'max' => 15],
[['rol'], 'string', 'max' => 2],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'nombreProfesor' => 'Nombre Profesor',
'apellidoProfesor' => 'Apellido Profesor',
'escuelaProfesor' => 'Escuela',
'rutProfesor' => 'Rut',
'claveProfesor' => 'Clave Profesor',
'rol' => 'Rol',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPlanificacions()
{
return $this->hasMany(Planificacion::className(), ['rutProfesor' => 'rutProfesor']);
}
}
Planificacion Model (planificacion.php)
<?php
namespace common\models;
use Yii;
class Planificacion extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'planificacion';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['fecha', 'fechaRevision', 'fechaPlanificacion'], 'safe'],
[['objetivosPlanificacion', 'actividad1', 'actividad2', 'actividad3', 'actividad4', 'obsActividad1', 'obsActividad2', 'obsActividad3', 'obsActividad4', 'contenidoActividad1', 'contenidoActividad2', 'contenidoActividad3', 'contenidoActividad4'], 'string'],
[['rutProfesor'], 'string', 'max' => 15],
[['nombreSesion', 'recursosUtilizadosPlanificacion', 'estadoActividad1', 'estadoActividad2', 'estadoActividad3', 'estadoActividad4', 'evalActividad1', 'evalActividad2', 'evalActividad3', 'evalActividad4', 'nombreSupervisor', 'asistencia'], 'string', 'max' => 255],
[['estado', 'rutSupervisor'], 'string', 'max' => 30],
[['rutProfesor'], 'exist', 'skipOnError' => true, 'targetClass' => Profesor::className(), 'targetAttribute' => ['rutProfesor' => 'rutProfesor']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'idPlanificacion' => 'Id Planificacion',
'rutProfesor' => 'Nombre Profesor',
'fecha' => 'Fecha',
'nombreSesion' => 'Nombre Sesion',
'objetivosPlanificacion' => 'Objetivos Planificacion',
'recursosUtilizadosPlanificacion' => 'Recursos Utilizados Planificacion',
'actividad1' => 'Actividad1',
'actividad2' => 'Actividad2',
'actividad3' => 'Actividad3',
'actividad4' => 'Actividad4',
'estadoActividad1' => 'Estado Actividad1',
'estadoActividad2' => 'Estado Actividad2',
'estadoActividad3' => 'Estado Actividad3',
'estadoActividad4' => 'Estado Actividad4',
'obsActividad1' => 'Obs Actividad1',
'obsActividad2' => 'Obs Actividad2',
'obsActividad3' => 'Obs Actividad3',
'obsActividad4' => 'Obs Actividad4',
'contenidoActividad1' => 'Contenido Actividad1',
'contenidoActividad2' => 'Contenido Actividad2',
'contenidoActividad3' => 'Contenido Actividad3',
'contenidoActividad4' => 'Contenido Actividad4',
'evalActividad1' => 'Eval Actividad1',
'evalActividad2' => 'Eval Actividad2',
'evalActividad3' => 'Eval Actividad3',
'evalActividad4' => 'Eval Actividad4',
'estado' => 'Estado',
'fechaRevision' => 'Fecha Revision',
'rutSupervisor' => 'Rut Supervisor',
'fechaPlanificacion' => 'Fecha Planificacion',
'nombreSupervisor' => 'Nombre Supervisor',
'asistencia' => 'Asistencia',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAsistencias()
{
return $this->hasMany(Asistencia::className(), ['idPlanificacion' => 'idPlanificacion']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRutProfesor0()
{
return $this->hasOne(Profesor::className(), ['rutProfesor' => 'rutProfesor']);
}
}
User Model (User.php)
<?php
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_SUPERVISOR = 1;
const ROL_PROFESOR = 2;
public $authKey;
/** #inheritdoc
/**
*/
public static function tableName()
{
return 'profesor';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return bool
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($claveProfesor)
{
return $this->claveProfesor === $claveProfesor;
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
public function isUserSimple($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 2]))
{
return true;
} else {
return false;
}
}
public function isUserAdmin($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 1]))
{
return true;
} else {
return false;
}
}
}
Planificacion Controller (planificacionController.php)
<?php
namespace frontend\controllers;
use Yii;
use common\models\Planificacion;
use common\models\PlanificacionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PlanificacionController implements the CRUD actions for Planificacion model.
*/
class PlanificacionController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Planificacion models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PlanificacionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Planificacion model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Planificacion model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Planificacion();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Planificacion model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Planificacion model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Planificacion model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Planificacion the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Planificacion::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
First, why you getting the error, is because ArrayHelper::getValue() require an array as first parameter, as it's purpose is to
Retrieves the value of an array element or object property with the
given key or property name.
And Yii::$app->user->identity->rutProfesor wouldn't yield an array, no, it would yield an single string, which is current rutProfessor in the session.
Then, on how you create the dropDownList you wanted, i suggest using an ArrayHelper::map() which is more straightfoward.
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::map(Profesor::find()->where([
'rutProfesor' => Yii::$app->user->identity->rutProfesor
])->all(), 'rutProfesor', 'nombreProfesor'); ?>
I beleive that code will do you good.
Happy coding. :)
I'm using the default Laravel 5.1 user registration. I have two tables: users and shops. When user registers, the app should insert a user in the table users, get the id and use it to register a shop. I've been reading the default AuthController.php but i didn't find anything. Here is the AuthController if it helps.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
//'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Get the path to the login route.
*
* #return string
*/
public function loginPath()
{
return route('login');
}
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
return route('home');
}
}
Solved, but now I have a Integrity constraint violation. Is this code correct?
protected function create(array $data)
{
$user = new User([
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
$user->role = 'shop_owner';
$user->remember_token = str_random(10);
$user->save();
$userId = $user->id;
Shop::create([
'name' => $data['s_name'],
'address' => $data['s_address'],
'CP' => $data['s_pcode'],
'Telephone' => $data['s_tlf'],
'contact_name' => $data['cp_name'],
'contact_num' => $data['cp_tlf'],
'id_user' => $userId
]);
return $user;
}
There you go:
protected function create(array $data)
{
$user = User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$userId = $user->id;
Shop::create([... use $userId here ...]);
return $user;
}
This goes to your controller:
public function store(Request $request) {
$user = User::create(Input::all());
$user->save();
$shop = Shop::create([..enter shop attributes or leave blank..]);
$user->shop()->save($shop);
}
You need to place the following code at the top of the Auth Controller
use App\Shop;