如何在laravel中绑定表单标记的路由URL

问题描述 投票:0回答:2

This is my form tag

    <form method="POST" action="{{ url("/post/{$article->id}/comment") }}">> 

This is my route

    Route::post('/post/{article}/comment', 'CommentController@store');

This is my commentcontroller method

    public function store(Article $article)
        {
             $comment = $article->comment->create([
            'body' => request('body'),
            ]);
            return back();
        }

show.blade.php

`@extends('master')
@section('content')
<!-- Example row of columns -->
<div class="container">
    <h1> {{ $articles->title }} </h1>
    <p> {{ $articles->body }} </p>
    <hr></hr>
    <div class="comment">
        <ul class="list-group"> 
            @foreach($articles->comments as $comment)
            <li class="list-group-item">
                <strong>
                    {{ $comment->created_at->diffForHumans()}} : &nbsp;
                </strong>
                {{ $comment->body }}
            </li>
            @endforeach
        </ul>
    </div>
    <!-- Here is comment form -->
    <hr>
    <div class="card">
        <div class="card-block">
            <form method="POST" action="{{ url ("/post/{$article->id}/comment") }}">> 
                {{ csrf_field() }}
                <div class="form-group">
                    <textarea name="body" placeholder="your comment here." class="form-control">  </textarea>

                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">Add Comment</button>
                </div>
            </form>
        </div>
        @include('partials.errors')
    </div>
</div>
@endsection`

当我试图在文章上添加评论时,我收到如下错误:

> Undefined variable: article (View: C:\xampp7\htdocs\Lara\resources\views\article\show.blade.php)

这有什么不对吗?帮帮我。提前致谢

php laravel laravel-5 blade
2个回答
0
投票

看来你没有通过$article查看。你还没有包含代码,但你有类似这样的地方:

return view('article.show');

而你应该有:

return view('article.show', compact('article'));

所以最后你在控制器中的show方法应该是这样的:

public function show(Article $article)
{
    return view('article.show', compact('article'));
}

0
投票

因为你实际上它是一篇文章,因为你在调用你的文章$articles(复数)。

在您的控制器中将$articles更改为$article,然后在您有文章的视图中更改它,例如$articles->body。在表单操作中使用它时,它将是正确的。

© www.soinside.com 2019 - 2024. All rights reserved.