简体   繁体   中英

Array to string conversion error in laravel 5.4

I'm trying to publish a post with register user in my laravel project But this Error happened I don't Know why please help me.

在此处输入图片说明 and my PostController is:

 public function __construct()
  {
    $this->middleware('auth')->except(['index','show']);
  }

public function index()
{
    $posts=Post::latest()->get();

    return view('posts.index',compact('posts'));
}

public function show(Post $post)
{

    return view('posts.show',compact('post'));
}

public function create()
{
    return view('posts.create');
}

public function store()
{

   $this->validate(request(),[
       'title'=>'required',
       'body' => 'required|min:15'
   ]);
   Post::create(request([
        'title' => request('title'),
        'body' => request('body'),
        'user_id' =>auth()->id()
        //auth()->user()->id
    ]));

    return redirect('/');
 }

How Can I fix it?

Try something like this.

public function store(Request $request)
{
    $model= new Model;
    $this->validate($request,[
        'title'=>'required',
        'body' => 'required|min:15'
    ]);

    $model->title= $request->title;
    $model->body= $request->body;
    $model->user_id= auth()->id();
    $model->save();  
    return redirect('/');
}

Try this code

public function store(Request $request)
{

   $this->validate(request(),[
       'title'=>'required',
       'body' => 'required|min:15'
   ]);
   Post::create([
        'title' => $request->title,
        'body' => $request->body,
        'user_id' =>auth()->id()
        //auth()->user()->id
    ]);
return redirect('/');
}

of course my code might not work properly but if you could provide me with create method details in post model i can help better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM