gpt4 book ai didi

laravel-5 - 传递给 Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() 的参数 1 必须是 Illuminate\Database\Eloquent\Model 的实例

转载 作者:行者123 更新时间:2023-12-01 19:21:27 26 4
gpt4 key购买 nike

我对 Laravel 还很陌生,我正在尝试将用户创建的帖子添加到数据库中。但是当我这样做时,出现以下错误:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, string given, called in C:\xampp\htdocs\lar\app\Http\Controllers\PostController.php on line
25 and defined

用户模型:

<?php

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;

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

发布模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

后 Controller :

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class postController extends Controller
{
public function postCreatePost(Request $request){
// Validation
$post = new Post();
$post->$request['body'];
$request->user()->posts()->save('$post');
return redirect()->route('dashboard');
}
}

发布路线:

Route::post('/createpost',[
'uses' => 'PostController@postCreatePost',
'as'=>'post.create'
]);

表单操作:

<form action="{{route('post.create')}}" method="post">

请告诉我如何解决这个问题..如何解决这个问题?提前谢谢你..:)

最佳答案

我想你想要的是这样的:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class postController extends Controller
{
public function postCreatePost(Request $request){
// Validation
$post = new Post();

// here you set the body of the post like that
$post->body = $request->body;

// here you pass the $post object not as string
$request->user()->posts()->save($post);
return redirect()->route('dashboard');
}
}

您需要将 $post 对象作为对象传递给 save 方法。当您需要执行此操作时,您正在执行以下操作:$user->posts()->save('$post'):$user->posts()->save($发布)

希望有帮助。

关于laravel-5 - 传递给 Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() 的参数 1 必须是 Illuminate\Database\Eloquent\Model 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40150958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com