在laravel 5.1中注册,更新用户信息并同时将数据发送到两个表

时间:2016-08-12 03:50:51

标签: php mysql laravel routes laravel-5.1

我需要注册一个新用户并将数据分别存储在两个表中,Users表将保存经典ID /名称/电子邮件/密码信息,而医生表将保存与新注册用户相关的不同信息,例如性别,age,user_pic等。我还需要编辑用户信息&将值保存在两个表中。如何实现这一点。谢谢。 我的路线文件是

Route::group([
    'middleware' => 'auth'
    ], function() {


        Route::get('/home', [
        'as' => 'admin',
        'uses' => 'AdminController@index'
    ]);

        Route::get('/profile', array('as' =>'profile' ,'uses' => 'ProfileController@index'));

    //     Route::get('/profile/{profile_id}',[
    //     'as' => 'profile',
    //     'uses' => 'ProfileController@index'
    // ]);

        Route::get('/mail',[
        'as' => 'mail',
        'uses' => 'MailController@index'
    ]);

    });

我的医生型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Doctor extends Model
{
    protected $fillable = [
        'name',
        'division_id',
        'district_id',
    ];

    public function district()
    {

        return $this->belongsto('App\District');
    }
    public function division()
    {

        return $this->belongsto('App\Division');
    }
}

1 个答案:

答案 0 :(得分:2)

创建表单并将POST方法发送到此路线:用户/保存

routes.php文件

Route::post('user/save', 'UserController@store')->name('addUser');

使用 artisan

创建一个控制器
php artisan make:comtroller UserController

UserController.php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;

class UserController extends Controller
{   
    public function store(Request $request)
    {
        // validate
        $this->validate($request, [
            'name' = 'required',
            'email' = 'required|email',
            'gender' = 'required',
            'age' = 'required'
        ]);

        // save users table
        $user = new App\User;
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->save();

        // save doctor table
        DB::table('doctor')
        ->insert(
            'id'        =>  $user->id,
            'gender'    =>  $request->input('gender'),
            'age'       =>  $request->input('age')
        );  

        // set a flush message and redirect()->back();
        return TRUE;
    }   
}