【问题标题】:Can't associate an user's id to a task Laravel无法将用户的 id 关联到任务 Laravel
【发布时间】:2019-04-27 06:19:56
【问题描述】:

我正在尝试使用 Laravel 5.7 创建一个待办事项列表网络应用程序。对于身份验证,我使用 php artisan make:auth.

当我尝试添加任务时,它只是吐出错误 500。

此外,显示手动创建的帖子也可以。

web.php

<?php
Route::get('/', 'TaskController@index')->name('index');
Route::post('/tasks', 'TaskController@store');
Route::delete(' /tasks/{task}', 'TaskController@destroy');
Auth::routes();

用户.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }
}

Task.php(该模型只是为所有其他模型添加了受保护的东西)

<?php

namespace App;

class Task extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

向上功能(任务)

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('text');
        $table->unsignedInteger('user_id');
        $table->timestamps();
    });
}

任务控制器

namespace App\Http\Controllers;
use App\Task;


class TaskController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $tasks = Task::where('user_id', auth()->id())->get();

        return view('index', compact('tasks'));
    }

    public function store()
    {
        $task = Task::create([
            'text' => request()->validate([
                'text' => 'required|max:255'
            ]),

            'user_id' => auth()->id()
        ]);

        return response()->json($task->id);
    }

    public function destroy(Task $task)
    {
        $task->delete();
    }
}

欢迎提出其他建议。

【问题讨论】:

    标签: php laravel authentication


    【解决方案1】:

    首先,您应该使用请求类来验证请求。因此,您的 store 方法如下所示:

    public function store(TaskRequest $taskRequest){}
    

    其次,在您的任务模型中添加以下内容。

    protected $fillable = [
       'text'
    ];    
    
    public static function boot()
    {
       static::creating(function($model){
          $model['user_id'] = Auth::user()->id;
       });
    }
    

    第三,你的 store 方法是这样的。

    public function store(TaskRequest $taskRequest)
    {
       $task = new Task($taskRequest->all);
       $task->save();
    
       return response()->json($task->id);
    }
    

    【讨论】:

    • 我照你说的做了,但是当我尝试显示索引页面时得到Undefined index: 'App\Task',基本上是显示某个用户的所有帖子的页面。
    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 2015-05-23
    • 2013-02-21
    • 2023-03-25
    相关资源
    最近更新 更多