【问题标题】:How can i get the id from a user that is creating an object and use it in the creation如何从创建对象的用户那里获取 id 并在创建中使用它
【发布时间】:2022-01-14 03:55:37
【问题描述】:

在我的代码中,我有一个“用户”模型和一个“ONG”模型,用户有一个 ong,而 ong 有一个“user_id”, 因此,当用户创建 Ong 时,我想获取用户(正在创建)ID 并插入 Ong user_id 列

用户只有在登录后才能创建 Ong

王模型

public function user(){

        return $this->belongsTo('App\Models\User');
    }

Ong 迁移

        Schema::create('ongs', function (Blueprint $table) {
            $table->bigIncrements('ong_id');
            $table->timestamps();
            $table->string('name',100);
            $table->smallInteger('user_id');
        });

用户迁移


        if(!Schema::hasTable('users')){
            Schema::create('users', function (Blueprint $table) {
                $table->id();
                $table->string('name', 100);
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password', 80);
                $table->rememberToken();
                $table->timestamps();
            });}

用户模型


    public function ong(){

        return $this->hasOne('App\Models\Ong');

    }

OngsController 有一个 store 方法

    public function store(Request $request)
    {
        $request->all();

        $request['user_id']= $id;

    }

但我怎样才能在其中获取“user_id”?

我正在使用来自 laravel/ui auth 的 Auth

现在只有这条路线,但这会变成表格

Route::group(['middleware'=>'web'],function(){
    Route::view('/criarOng', 'ongs.create');
});

创建表单


{!! Form::open([
        'method'=>'post', 'route' => 'ongs.store'
    ]) !!}
    {!! Form::label('name', 'Nome da Ong') !!}
    {!! Form::text('name') !!}
    {!! Form::select('estado',['SP'=>'SP', 'RJ'=>'RJ'], null) !!}
    {!! Form::label('cidade', 'Cidade da ong') !!}
    {!! Form::text('cidade') !!}
    {!! Form::submit('Criar') !!}
    

    {!! Form::close() !!}

【问题讨论】:

  • 使用 $request->user() 获取当前登录的用户实例。

标签: php laravel laravel-8


【解决方案1】:

您需要在ong表上设置外键。

 Schema::create('ongs', function (Blueprint $table) {
            $table->bigIncrements('ong_id');
            $table->timestamps();
            $table->string('name',100);
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

然后在创建时你可以使用

public function store(Request $request)
    {
        $request->all();

        $user_id = Auth::user()->id;

    }

然后在您的 ONG 模型中

public function ong(){

        return $this->hasMany('App\Models\Ong');

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    相关资源
    最近更新 更多