Reputation: 55
here is my controller named CommentController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use Auth;
class CommentsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return view('comments.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$comment= new Comment();
$comment->user_id=Auth::user()->id;
$comment->body=$request->body;
$comment->save();
return back();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show()
{
//
$comments=comment::all();
return view('comments',['comments'=>$comments]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
here is my layout code named create.blade.html
<html>
<head>
<h1>DONE</h1>
</head>
<body>
<div class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>Comments</h3></header>
<form action="/comments" method="post">
{{csrf_field()}}
<div class="form-group">
<textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your review on above game"></textarea>
</div>
<button type="submit" class="btn btn-primary">Post Comment</button>
</form>
</div>
</div>
<?php foreach($comments as $comment) ?>
<h1><?php echo $comment ?> <h1>
</body>
</html>
Here is my routes code named as web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::resource('comments','CommentsController');
Route::get('comments.create','CommentsController@show');
?>
Now here whatever data I am submitting is getting entered in database but when I trying to display that data it is giving me error Undefined variable: comments. Thanks in advance :-)
Upvotes: 1
Views: 29
Reputation: 163798
That's because you're not passing $comments
variable from create()
method which should look like this:
public function create()
{
$comments = comment::all();
return view('comments.create', ['comments' => $comments]);
}
Also remove Route::get('comments.create'
, because it's a bad idea to try to override resource routes. Use create()
to display the form and show()
to display one comment.
Upvotes: 1