【问题标题】:Laravel Doesn’t Take a Parameter in a FunctionLaravel 不接受函数中的参数
【发布时间】:2019-06-26 04:25:54
【问题描述】:

我正在使用 API 和 Ajax 制作一个简单的聊天应用程序;问题是当我发出 Ajax 请求并将聊天对话存储在我的数据库中时,如果对话存在,则只保存消息。 但是当我保存消息时,请求不带 ID,但当我保存聊天时带它。

Laravel

public function storeMsj(Request $req)
{
    $existChat = $this->existsChat($req->id);
    if ($existChat == 0) {
        Chat::create([
            'user' => $req->id,//here take the request
            'read' => 0,
        ]);

        Message::create([
            'message_content' => $req->msj,
            'from' => $req->id,//here not take the request
            'to' => 1,
        ]);
    } else {
        Message::create([
            'message_content' => $req->msj,
            'from' => $req->id,
            'to' => 1,
        ]);
    }

    return Response::json($req->id);//the response show correctly the request
}

JS

function storeMsj(){
    let msj = document.querySelector('.msg').value;
    let id = idUser.firstElementChild.innerHTML;

    fetch('/api/storeMsj',{
        method: 'POST',
        headers:{
            'Accept': 'application/json, text/plain, */*',
            'Content-type': 'aplication/json'
        },
        body: JSON.stringify({
            msj: msj,
            id: id
        }),
    })
    .then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then(response => console.log('Success:', response)); 
}

【问题讨论】:

  • userfrom 字段可以填写吗?请提供您为ChatMessage 模型中的$fillable$guarded 属性设置的任何值。
  • 不,这是问题所在,谢谢!

标签: javascript ajax laravel api fetch


【解决方案1】:

在 Laravel 质量分配中,您需要在模型上指定可填充或受保护的属性,因为所有 Eloquent 模型都默认防止质量分配。

    class Flight extends Model
    {
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];
   }

【讨论】:

    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多