Как решить 500 (Внутренняя ошибка сервера) SQLSTATE [23000]: Нарушение ограничения целостности: 1048 Столбец 'user_id' не может быть пустым? - PullRequest
0 голосов
/ 05 апреля 2020

Я использую топор ios в vue в laravel, чтобы опубликовать метод. И я получаю следующую ошибку:

enter image description here

CommentController. php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Comment;
use Auth;

class CommentController extends Controller {
    public function index(Post $post){
        return response()->json($post->comments()->with('user')->latest()->get()); //latest is used to sort them(the latest one in the tops)
    }

    public function store(Request $request, Post $post){
        $comment = $post->comments()->create([
            'body' => $request->body,
            'user_id' => Auth::id() //Auth::id();
        ]);
        $comment = Comment::where('id', $comment->id)->with('user')->first();
        return $comment->toJson();
    }
}

Vue. js :

<script>
    const app = new Vue({
      el: '#app',
      data: {
          comments: {},
          commentBox: '',
          post: {!! $post->toJson() !!},
          user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}
      },
      created: function() {
        this.getComments();
      },
      methods: {
        getComments: function(){
          axios.get(`/api/posts/${this.post.id}/comments`)
            .then(res => {
              this.comments = res.data;
            });
        },
        postComment: function() {
          axios.post(`/api/posts/${this.post.id}/comment`,{
            body: this.commentBox,
            user_id: this.user.id
          })
            .then(response => {
              console.log(response);
              this.comments.unshift(response.data);
              this.commentBox = '';
            })
            .catch(error => {
              console.log(this.user);
              console.log(error.response);
            });
        }
      }
    });

   </script>

Когда я передаю user_id в CommentController. php жестко, как показано ниже, ошибка исчезает, и все успешно выполняется:

$comment = $post->comments()->create([
        'body' => $request->body,
        'user_id' => '4' //Auth::id();
    ]);

Модель комментария:

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $fillable = [
        'body', 'user_id'
    ];

    public function post(){
        return $this->belongsTo('App\Post');
    }

    public function user(){
        return $this->belongsTo('App\User');
    }
}

api. php маршруты:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('posts/{post}/comments','CommentController@index');
Route::post('posts/{post}/comment','CommentController@store');

Route::middleware('auth:api')->group(function () {

});

app / Middlware / Authentication. php

<?php

namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

Кто-нибудь знает, почему Auth :: id () в контроллере нет ш?

Ответы [ 2 ]

1 голос
/ 05 апреля 2020

sry я написал неправильный ответ, потому что я не мог написать комментарий

вы используете неправильный класс. попробуйте импортировать это

use Illuminate\Support\Facades\Auth;
0 голосов
/ 05 апреля 2020

Попробуйте это:

$user = Auth::user();

$comment = $post->comments()->create([
    'body' => $request->body,
    'user_id' => $user->id
]);
...