Reputation: 21
i am new to code and wondering why my comment id is not linking to the correct post id.
This is my comment controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Tweet;
use App\Models\User;
use App\Models\Comment;
class CommentController extends Controller
{
public function show()
{
return view('comments',[
'tweets' => Tweet::all()
]);
}
public function store(Tweet $tweet)
{
$attributes = request()->validate(['comment_body' => 'required|max:255']);
Comment::create([
'user_id' => auth()->id(),
'tweet_id' => $tweet->id,
'comment_body' => $attributes['comment_body']
]);
return redirect('/comments/{$tweet->id}');
}
}
This is my comment.blade.php file
x-app>
<div class="border border-blue-400 rounded-lg px-8 py-6 mb-8">
{{dd($tweets)}}
@foreach ($tweets as $tweet)
<form method="POST" action="/comments/{{$tweet->id}}">
@csrf
@endforeach
<textarea
name="comment_body"
class="w-full"
placeholder="Reply to this tweet"
required
autofocus
>
</textarea>
<hr class="my-4">
<footer class="flex justify-between items-center">
<img
src="/images/twitter.jpg"
alt=""
class="mr-2 rounded-full"
width="50"
>
<button type="submit" class="bg-blue-500 hover:bg-blue-600 rounded-lg shadow px-10 text-white h-10">Comment</button>
</footer>
</form>
@error('body')
<p class="text-red-500 text-sm mt-2">{{ $message }} </p>
@enderror
</div>
<div class="border border-gray-300 rounded-lg">
<p class="p-4">No comments</p>
</div>
</x-app>
The main problem is I hit comment and instead of it entering the database as it should e.g I comment on a tweet with an id of 2 in the database and the comment will have a tweet id of 1 which is what is meant to link them but instead, all the comments are going to the tweet id 1.
Upvotes: 0
Views: 69
Reputation: 899
Your controller method is expecting a 'Tweet' Model, not $tweet->id
, which you are posting.
You can confirm this by doing a print_r on $tweet
in the store method of your controller.
print_r($tweet);
Change your form action to be
<form method="POST" action="/comments/{{$tweet}}">
IF YOU ARE NOT USING A RESOURCE ROUTE
Your POST route for this action must be setup like this:
Route::post('/comments/{tweet}, 'CommentController@store');
As per JoshBonnick's comment, the form opening tag is within your @foreach
loop in the blade example you gave, but the closing is not, you probably want to move your @endforeach
below your closing </form>
tag
You also have an error in your redirect in the controller, you do not need the braces {}
around {$tweet->id}
Upvotes: 1
Reputation: 842
The POST
method will not accept the ID from the action. You may use a hidden field for ID in the form.
Upvotes: 0