У меня есть форма редактирования, где большая часть данных формы будет отправлена в таблицу пользователей. Для пользователей, которым требуется лицензия, их информация будет размещена в таблице лицензий, поля лицензии видны только для соответствующего типа пользователя. I.Е, если пользовательский тип является регистратором, тогда они не будут видеть поля лицензии, но если тип пользователя будет дантистом, тогда будут отображаться поля и т. Д. У меня есть user_id внутри таблицы лицензий, чтобы я мог связать пользователей с лицензиями. Я создал новую модель под названием красноречивой лицензия большинство моей работы делается в контроллере обновления .........Laravel 4 как отправить данные формы в разные таблицы
лицензий Модели
class License extends Eloquent {
protected $table = 'temps_license';
public function user()
{
return $this->belongsTo('User');
}
}
Контроллер
public function update($id)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'firstname' => 'required|min:3|alpha',
'lastname' => 'required|min:3|alpha',
'zipcode' => 'required|min:5|numeric',
'temp_experience' => 'required|min:1|max:50|numeric',
'temp_travel' => 'required|numeric',
'temp_hourly_rate' => 'required|numeric|min:10'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('user/profile/' . $id . '/edit')
->withErrors($validator)
->withInput();
} else {
$software_checked = Input::get('software');
if(is_array($software_checked))
{
$imploded_software = implode(',', $software_checked);
}
// store
$user = User::find($id);
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->zipcode = Input::get('zipcode');
$user->temp_experience = Input::get('temp_experience');
$user->temp_travel = Input::get('temp_travel');
$user->temp_hourly_rate = Input::get('temp_hourly_rate');
$user->temp_software_experience = $imploded_software;
if($user->save()) {
if($user->usertype == 'dental hygienist' && !$user->license->temp_id) {
$license = new License();
$license->temp_id = $id;
$license->license_expiration_date = Input::get('expiration_date');
$license->save();
}
// redirect
Session::flash('message', 'Successfully updated profile!!');
return Redirect::to('user/profile/'.$id.'');
}
}
}
ПОЛЬЗОВАТЕЛЯ МОДЕЛЬ
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
public static function getTemps()
{
// Create a array of allowed types.
$types = array('dental hygienist', 'dentist', 'dental assistance');
// Get what type the user selected.
$type = Input::get('temptype');
//Get user location
//$location = Input::get('zipcode');
// Make sure it is a valid type.
if(!in_array($type, $types))
{
return App::abort(500, "Invaild temptype.");
}
$temps = DB::table('users')
->join('availability', 'users.id', '=', 'availability.userid')
->select('users.id', 'users.firstname', 'users.lastname', 'users.zipcode', 'users.salary', 'availability.dateavailable')
->where('usertype', $type)
//->where('zipcode', $location)
->get();
return $temps;
}
public function license()
{
return $this->hasOne('License');
}
Модифицированного контроллер
Это работает лучше, но всякий раз, когда я обновить дату пользователей истечения срока действия, состояние или номер лицензии он работает, и он обновляет, но есть повторяющиеся записи в базе данных .....
if($user->usertype == 'dental hygienist' || $user->usertype == 'dentist' && !$user->license->temp_id) {
$license = new License();
$license->user_id = $id;
$license->temp_id = $id;
$license->license_expiration_date = Input::get('expiration_date');
$license->license_number = Input::get('license_number');
$license->license_state = Input::get('license_state');
$license->save();
}
Благодарим за совет. Я обновил свой код, чтобы показать свою модель пользователя и ваше предложение. Я получаю неизвестную ошибку столбца.Когда я удаляю эту строку кода в методе сохранения! $ User-> license-> temp_id, информация сохраняется просто отлично. Однако, когда я пытаюсь обновить информацию, новая запись для этого пользователя создается, она не обновляется .... Ошибка говорит Неизвестный столбец «temps_license.user_id» в разделе where. Я думаю, что он ищет столбец user_id в таблице temp_license, но его нет. Я связываю эти две таблицы с помощью temp_id. Я могу удалить его и добавить user_id @RCV – elodev
Я удалил '&&! $ User-> license-> temp_id' –
Если': find ($ id) 'возвращает модель, то она должна обновляться. –