Edit3: Could a reason be because both controllers are leading to the same page?
Edit2: Still not working after the answers I got.
Edit: Error one is solved, now I'm getting:
Undefined variable: project (View:
/var/www/resources/views/pages/showProject.blade.php)
Can this be because both variables are leading to the same page? The projects variable was working perfectly before the comment system.
public function index()
{
$projects = Project::all();
return view('pages.projects', compact('projects'));
}
Project variable declare.
I'm trying to get my comments from my database to show on a specific 'project page' in the laravel 5 project I'm working on. The idea is that the user can add art projects and other users can comment on them, but whenever I try to visit the page I get
Undefined variable: comments (View:
/var/www/resources/views/pages/showProject.blade.php)
This is my controller
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
public function store()
{
$input = Request::all();
$comment = new Comment;
$comment->body = $input['body'];
$comment->project_id = $input['project_id'];
$comment->user_id = Auth::user()->id;
$comment->save();
return redirect('projects/'.$input['project_id']);
}
These are my routes
// add comment
Route::post('projects/{id}','CommentController#store');
// show comments
Route::post('projects/{id}','CommentController#index');
And my view
#if (Auth::check())
<article> <!--Add comment -->
<br/>
{!! Form::open() !!}
{!! form::text('body', null, ['class' => 'form-control']) !!}
<br/>
{!! Form::Submit('Post Comment', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::hidden('project_id', $project->id) !!}
{!! Form::close() !!}
<br/>
</article>
<article>
#foreach ($comments as $comment)
<article>
<p>Body: {{ $comment->body }}</p>
<p>Author: {{ $comment->user->name }}</p>
</article>
#endforeach
</article>
#else
<p>Please log in to comment</p>
#endif
The Model
class Comment extends Model
{
//comments table in database
protected $guarded = [];
// user who has commented
public function author()
{
return $this->belongsTo('App\User','user_id');
}
// returns post of any comment
public function post()
{
return $this->belongsTo('App\Project','project_id');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public $timestamps = false;
}
Is there any way I can solve this?
Thanks in advance
First, you need to make sure that you are aliasing your 'Comment' model in your controller. This is done with the use statement.
use App\Comment;
class CommentController extends Controller
{
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
}
Second, you will need to change your route for showing comments from a POST request to a GET request. At the moment you are making identical routes and furthermore GET is the correct request type for retrieving data.
Route::get('projects/{id}','CommentController#index');
Third, you are referencing a $project variable in your view, but never passing it in from the controller. That needs to reference something.
I think your relationship is wrong. Try this:
Comment model:
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
User model:
class User extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
In the view you can use:
#foreach($comments as $comment)
<p>{{ $comment->user->name }}</p>
#endforeach
I needed to empty the show in the commentsController and only use it for saving the comments. For showing them I made an extra function in my projectsController. It ended up being this;
public function show($id)
{
$project = Project::findOrFail($id)->load("User");
$input = Request::all();
//-----------------------DB-----------------------------//
$project_comments = DB::table('comments')
->select('body', 'name')
->where('project_id', '=', $id)
->join('users', 'users.id', '=', 'user_id')
->get();
//-----------------------DB-----------------------------//
return view('pages.showProject', ['project' => Project::findOrFail($id), 'comments' => $project_comments]);
}
Related
I'm looking for some help. I've searched on other topics, and saw what is the problem approximatively, but didn't succeed to fix it on my code.
Now the question is: I have NotFoundHttpException when i try to submit an update on my code.
Here is the Controller and my function update
<?php
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use App\T_collaborateurs_table;
class testing extends Controller
{
public function index()
{
$user = T_collaborateurs_table::all();
return view ("read", compact("user"));
}
public function create()
{
return view("create");
}
public function store(Request $Request)
{
T_collaborateurs_table::create(Request::all());
return redirect("index");
}
public function show($id)
{
$user=T_collaborateurs_table::find($id);
return view("show", compact("user"));
}
public function edit($id)
{
$user=T_collaborateurs_table::find($id);
return view("update", compact("user"));
}
public function update(Request $Request, $id)
{
$user = T_collaborateurs_table::find($id);
$user->update(Request::all());
return redirect("index");
}
}
Now the routes
Route::get("create", "testing#create");
Route::post("store", "testing#store");
Route::get("index", "testing#index");
Route::get("show/{id}", "testing#show");
Route::get("edit/{id}", "testing#edit");
Route::patch("update/{id}", "testing#update");
And now the view update.blade.php
<body>
{{Form::model($user, ['method'=>'patch', 'action'=>['testing#update',$user->id]])}}
{{Form::label('Id_TCa', 'ID')}}
{{Form::text('Id_TCa')}}
{{Form::label('Collaborateur_TCa', 'collab')}}
{{Form::text('Collaborateur_TCa')}}
{{Form::label('Responsable_TCa', 'resp')}}
{{Form::text('Responsable_TCa')}}
{{Form::submit("update")}}
{{Form::close()}}
</body>
Here the route:list
I'm sorry if my words are not very understable...
Thank you all for your time.
{{Form::model($user, ['method'=>'PATCH', 'action'=> ['testing#update',$user->id]])}}
Or try to use 'route' instead of 'action',to use 'route' you just need a little edit in your update route.
Route::patch("update/{id}", array('as' => 'task-update', 'uses'=>'testing#update'));
in your view:
{{Form::model($user, ['method'=>'PATCH', 'route'=>['task-update',$user->id]])}}
And please follow the convention of class naming. Your class name should be 'TestingController' or 'Testing'.
You could try method spoofing by adding
{{ method_field('PATCH') }}
in your form and change the form method to POST
{{ Form::model($user, ['method'=>'POST', 'action'=>['testing#update', $user->id]]) }}
add the id as an hidden field
{{ Form::hidden('id', $user->id) }}
access the id in the controller as
public function update(Request $Request)
{
$id = Input::get('id');
$user = T_collaborateurs_table::find($id);
$user->update(Request::all());
return redirect("index");
}
also need to modify your route accordingly
Route::patch("update", "testing#update");
Try using on function update:
return redirect()->route('index');
I want to make a user wall where all of his post will be loaded with those who has given comment under it. So I have defined following relations in my User model.
public function post()
{
return $this->hasMany(Post::class);
}
public function comment()
{
return $this->hasMany(Comment::class);
}
My Post model:
public function user()
{
return $this->belongsTo(User::class);
}
public function post_comment()
{
return $this->hasMany(Comment::class);
}
My Comment model:
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
In my Controller:
public function wall($id)
{
$all_post = Post::where('user_id',$id)->get();
return view('client.wall',['all_post'=> $all_post]);
}
in my Blade file:
#foreach($all_post as $post)
Post Title: {{ $post->title }} //gets the title properly
#foreach($post->post_comment as $comment) //this foreach loop throwing erros
Name: {{ $comment->user->name }}
Comment: {{ $comment->description }}
#endforeach
#endforeach
Probably my logic is wrong to load the comments from database. Because I am getting errors.
try this ad share if you still have an error
Controller
public function wall($id)
{
$all_post = Post::where('user_id',$id)->with('post_comment')->get();
return view('client.wall')->with('all_post',$all_post);
}
VIEW
#foreach($all_post as $post)
Post Title: {{ $post->title }} //gets the title properly
#foreach($post->post_comment as $comment)
Name: {{ $comment->user->name }}
Comment: {{ $comment->description }}
#endforeach
#endforeach
I am getting error
method orderBy does not exist on my view.
This is my view:
#foreach($post->comments->orderBy('created_at', 'desc') as $comment)
{{ $comment->comments }}
#endforeach
#stop
This is my controller:
public function store(Request $request)
{
$post = new post;
$post->title = $request->title;
$post->save();
return redirect()->route('rules');
}
public function show($title)
{
$post = post::where('title', $title)->first();
return view('post.show', compact('post'));
}
public function storecomment(request $request)
{
$comment = new comment;
$comment->post_id = Crypt::decrypt(Input::get('post_id'));
$comment->comments = $request->comments;
$comment->save();
return redirect()->route('rules');
}
still getting an error.
You are trying to use orderBy() in a Collection object, not in a query.
To make this work exactly as you are doing, you have to do:
#foreach($post->comments()->orderBy('created_at', 'desc')->get() as $comment)
{{ $comment->comments }}
#endforeach
But, this way is not the best way to do it.
To make the code clear, you should add this to comments() method or create another method that orders the query inside the model.
maybe this is a simple problem but for me, am I newbie in Laravel, it's problem, so I have three table
Articles, User, Comments. They have this relationship
In page http://localhost/users/{user_name} I want to get all articles and all comments that belongs to this user.
Three Model looks like this:
User
public function articles()
{
return $this->hasMany('App\Article');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
Article
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
and
Comment
public function user()
{
return $this->belongsTo('App\User');
}
public function article()
{
return $this->belongsTo('App\Article');
}
My Controller Show method looks like this:
public function show(User $user)
{
$user->with(['comments','articles'])->get();
return view('users.show', compact('user', 'comments', 'articles'));
}
In view I have everything what I need
{{ dump($user) }}
{{ dump($user->articles) }}
{{ dump($user->comments) }}
{{ dd() }}
and with foreach I get needed attributes, but how do I create link where I can see link to article and comment to her
#foreach($user->comments as $comment)
<div class="block">
//article title
<div></div>
<div>{{ $comment->comment }}</div>
#endforeach
To show article I use title of article, not ID.
Thanks
First, 'comments' and 'articles' here don't do anything.
return view('users.show', compact('user', 'comments', 'articles'));
As for the link,
{{ $comment->article->title }}
I resolved this issue, updated my controller:
public function show(User $user)
{
$params = Comment::where('user_id', $user->id)->get()
return view('users.show', compact('user', 'params'));
}
It's works like I need but I think that there are better way to resolve this.
Okay so I just started learning Laravel and its fantastic. I just got stuck trying to retrive all the post from a user. Here is my code
models/User.php
public function posts()
{
$this->hasMany('Post');
}
models/Post.php
public function user()
{
$this->belongsTo('User');
}
controller/UserController.php
public function getUserProfile($username)
{
$user = User::where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
views/user/index.blade.php
<div class="show-post">
<ul>
<li>{{ $user->posts }}</lo>
</ul>
</div>
I also tried:
#foreach($user->posts as $post)
<li>{{$post->post}}</li>
#endforeach
So im having trouble displaying the post for each specific user. Thank you.
So with the help of #WereWolf- The Alpha I was able to solve it and make my code better, If you notice I forgot to return my relationship functions. example:
Notice I hadn't returned it before
models/Post.php
public function users()
{
return $this->belongsTo('users');
}
But also the way I was querying my database was inefficient so Alpha showed me Eager Loading
http://laravel.com/docs/eloquent#eager-loading
example of controller
public function getUserProfile($username)
{
$user = User::with('posts')->where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
and finally the view:
div class="show-post">
#foreach($user->posts as $post)
{{ $post->post }}
#endforeach
</div>
Actually $user->posts returns a collection of Post model so when you try this
{{ $user->posts }}
Laravel tries to echo that collection object which is not possible. You may try foreach loop instead:
#foreach($user->posts as $post)
{{ $post->somepropertyname }}
#endforeach
It's also possible to do something like this:
// Get first post->somepropertyname
{{ $user->posts->first()->somepropertyname }}
// Get last post->somepropertyname
{{ $user->posts->last()->somepropertyname }}
// Get first post->somepropertyname (same as first)
{{ $user->posts->get(0)->somepropertyname }}
// Get second post->somepropertyname from collection
{{ $user->posts->get(1)->somepropertyname }}
// Get the post->somepropertyname by id (post id) 2
{{ $user->posts->find(2)->somepropertyname }}
Also you may use eager loading like this (better):
$user = User::with('posts')->where('username', '=', $username)->first();
You may like this article about Cocllection.
Update: Also use return in model methods, like:
public function posts()
{
return $this->hasMany('Post');
}