0

I'm creating a news feed kind of thing where users can post anything and the post will have comments also. I'm able to create the newsfeed and the comment section, but my real problem is I'm not able to show the comments which belongs to the post. Right now all the comments are displayed under every news feed. Though I've declared the eloquent relationship between feed and comment but still I'm not able to save the feed_id in comment table.

This is my FeedsController:-
<?php namespace App\Http\Controllers;
use Request;
use Auth;
use Sentinel;
use App\Feed;
use App\Http\Requests;
use App\Blog;
use App\Http\Controllers\Controller;
use App\Comment;

class FeedsController extends Controller
{
public function index() {

  $comments = Comment::latest()->get();
  $feeds = Feed::where('user_id', Sentinel::getUser()->id)->latest()->get(); 
  $blogs = Blog::latest()->simplePaginate(5);
  $blogs->setPath('blog');
  return view('action.index')->with('feeds', $feeds)->with('comments', $comments)->with('blogs', $blogs);
}

public function store(Requests\CreateFeedRequest $request){
    $requet = $request->all();
    $request['user_id'] = Sentinel::getuser()->id;

  Feed::create($request->all());


  return redirect('home');
}

 public function storecomment(Requests\CommentRequest $request, Feed $feed)
 {

$comment = new Comment;
$comment->user_id =Sentinel::getuser()->id;
$comment->feed_id = $request->feed_id;
$comment->comment = $request->comment;
$comment->save();
  return redirect('home');
}  
}

This is the models: Comment model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
 protected $fillable = [
 'comment',
 'user_id',
 'feed_id'
 ];

 public function feed()
 {
    return $this->belongsTo('App\Feed');
 }

 public function user()
 {
    return $this->belongsTo('App\User');
 }
 }

Feed model:

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
 protected $fillable = [
 'feed_id',
 'user_id',
 'feed_content'
 ];

 public function user()
 {
    return $this->belongsTo('App\User');
 }

 public function comment()
 {
    return $this->hasMany('App\Comment');
 }
}

User model:-

<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;


class User extends EloquentUser {


/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes to be fillable from the model.
 *
 * A dirty hack to allow fields to be fillable by calling empty fillable array
 *
 * @var array
 */
protected $fillable = [];
protected $guarded = ['id'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password', 'remember_token'];

/**
* To allow soft deletes
*/
use SoftDeletes;

protected $dates = ['deleted_at'];



public function feeds() 
{
    return $this->hasMany('App\Feed');
}

public function comment()
 {
    return $this->hasMany('App\Comment');
 }
 }

This is my feed.blade.php where I'm displaying the feeds output and commnets

@foreach($feeds as $feed)
<article class="media">
    <div class="well">
        <div class="pull-left"> 
            <img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic)  }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
         </div>
        <strong>{{ $feed->user->first_name }} 
                {{ $feed->user->last_name }}
                <small> posted </small>
         </strong>
                {{ $feed->created_at->diffForHumans() }}<br><hr>
                {{ $feed->feed_content }}

            <hr>
            {!! Form::open(['url' => 'home/{storecomment}']) !!}
                <div class="form-group">
                    {!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
                </div>

                <div class="form-group feed_post_submit">
                    <a href="/home">{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}</a>
                </div>
            {!! Form::close() !!}

            @foreach($comments as $comment)
                <div class="pull-left"> 
                    <img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic)  }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
                </div>
                {{ $comment->user->first_name }} 
                {{ $comment->created_at->diffForHumans() }}
                {{ $comment->comment }}<hr>
            @endforeach
    </div>
</article>
@endforeach

Can anyone tell me how to store the feed_id into comment table and displaying the comments according to the feed. Thank You. I'm using Laravel 5.1

Vikram Shaw
  • 11
  • 1
  • 7

1 Answers1

0

Based on our lengthy convo -

To save the feed_id (which is our foreign key for future relationships), you need to set/send the feed_id in your POST request. Laravel is not magic and won't know this automatically. You can do this by adding a hidden input, like so:

<input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" />

In your FeedController, change your index to this:

public function index() {

  // $comments = Comment::latest()->get(); remove this
  // notice the "with" below. I'm eager loading in relations here
  $feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get(); 
  $blogs = Blog::latest()->simplePaginate(5);
  $blogs->setPath('blog');
  return view('action.index', compact('feeds', 'blogs'));
}

Feed Model should have the correct relationships, as below:

class Feed extends Model
{
     protected $fillable = [
     'feed_id',
     'user_id',
     'feed_content'
     ];

     public function user()
     {
        return $this->belongsTo('App\User', 'id', 'user_id');
     }

     public function comments()
     {
        return $this->hasMany('App\Comment', 'feed_id', 'feed_id');
     }
}

Comment Model should have the correct relationships, as below:

class Comment extends Model
{
     protected $fillable = [
     'comment',
     'user_id',
     'feed_id'
     ];

     public function feed()
     {
        return $this->belongsTo('App\Feed');
     }

     public function user()
     {
        return $this->hasOne('App\User', 'id', 'user_id');
     }
}

Now you should be able to run your foreach as you currently have it.

Mike Barwick
  • 6,288
  • 6
  • 51
  • 76
  • Thanks for the quick reply. I used your way also but showing error Call to undefined method Illuminate\Database\Query\Builder::comments(). When tried to did midification in $feeds section. Even the feed-id is not being stored. – Vikram Shaw Jul 11 '16 at 22:17
  • "You're comment save method looks correct. If you put return $request->all() as the first line in that method, what does it return?" – Mike Barwick Jul 11 '16 at 22:19
  • "Also, in your Feed model, pluralize comment to `public function comments()` for better readability." – Mike Barwick Jul 11 '16 at 22:20
  • If I'm using return $request->all(); in first line of store comment method then it is returning this {"_token":"Xw9qTEbg7VN2WA5ywDH8UE6q9UjQ5DmWoXVQb9kq","comment":"checking Comment"} Checking comment is the comment which I wrote in comment section. – Vikram Shaw Jul 11 '16 at 22:40
  • Okay...that explains it then. Where's the $request values you're trying to save? Where's `$request->feed_id` and `$request->comment` – Mike Barwick Jul 11 '16 at 23:04
  • So what modification should I do in order to get all the comments which belongs to the feeds. – Vikram Shaw Jul 11 '16 at 23:13
  • What form is submitting to the `storecomment` method? One step at a time here. This method is wrong and hence why it's not saving. You're not passing any of the values you're trying to save. – Mike Barwick Jul 11 '16 at 23:14
  • In storecomment method comment form is being submitted and in database I've feed_id, comment and user_id table. In which I'm getting user_id and comment not feed_id. This feed_id is same as feeds table feed_id. – Vikram Shaw Jul 11 '16 at 23:19
  • Huh? You need to pass the `feed_id` when submitting the form dude. Right now, this doesn't exist: `$request->feed_id`. Show this form where someone enters a comment please. – Mike Barwick Jul 11 '16 at 23:21
  • But the thing is I want this thing to be done automatically with eloquent relationship or any other method because no user will know the feed_id of the feed. It should be connected in such a way that if any user comment on any feed then the feed_id of the feed will automatically be saved in comment feed_id and using the relationship we can display the comment which belongs to the feed – Vikram Shaw Jul 11 '16 at 23:27
  • How is Laravel suppose to know the feed_id?!? It's not magic man lol. I don't think you truly understand how relationships work. You NEED to pass that value to the form request. Add a hidden input with name "feed_id"...make it's value the feed id, etc. – Mike Barwick Jul 11 '16 at 23:33
  • Can you tell me how to link the hidden input with value feed_id to the id of the feeds. – Vikram Shaw Jul 12 '16 at 08:51
  • Oh man. If you haven't already, I'd look at watching some videos at Laracasts.com and brush up on basic HTML. `{{ Form::hidden('feed_id', $feed->id) }}` or standard way, `` – Mike Barwick Jul 12 '16 at 14:39
  • What's happens when you return `$feeds` in your controller? Show me that result – Mike Barwick Jul 13 '16 at 06:18
  • And make sure the relationships are set up properly, as I stated – Mike Barwick Jul 13 '16 at 06:19
  • Thanks for replying and because of you only I'm able to save the feed_id. But I'm not able to show the comments though I have used the below code. – Vikram Shaw Jul 13 '16 at 06:24
  • @foreach($feed->comments as $comment)
    Image
    {{ $comment->user->first_name }} {{ $comment->created_at->diffForHumans() }} {{ $comment->feed->comment }}
    @endforeach
    – Vikram Shaw Jul 13 '16 at 06:25
  • In commentstore method if I'm writing $feeds = Feed::all(); and return $feeds, then it is returning all the feeds but if I'm writing only return $feeds then it is returning Undefined variable: feeds. – Vikram Shaw Jul 13 '16 at 06:55
  • Of course you need to grab the feed first. Look at my answer. First code example man. You should also check out laracasts.com and go through the learners videos. It'll help. :) – Mike Barwick Jul 13 '16 at 06:57
  • Problems were running into now are entry level. Nevermind complex relationships. There's only so much I can do. – Mike Barwick Jul 13 '16 at 06:59
  • Thanks anyways for taking time and explaining the things which I didn't knew. – Vikram Shaw Jul 13 '16 at 07:03
  • Return Feed::with('comments')->get(); tell me what that displays. Only one record. Not the whole object. – Mike Barwick Jul 13 '16 at 07:04
  • {"feed_id":47,"user_id":1,"feed_content":"now the feed_id is saved ","created_at":"2016-07-12 19:27:52","updated_at":"2016-07-12 19:27:52","comments":[]} – Vikram Shaw Jul 13 '16 at 07:19
  • Okay. Perfect. I see comments appears in the array. Relationship is just about set. Now in Feed model, in the comments method change it to this `return $this->hasMany('App\Comment', 'feed_id', 'feed_id');` – Mike Barwick Jul 13 '16 at 07:24
  • [{"feed_id":55,"user_id":1,"feed_content":"First status","created_at":"2016-07-13 07:31:10","updated_at":"2016-07-13 07:31:10","comments":[{"id":82,"feed_id":55,"comment":"first comment","user_id":1,"created_at":"2016-07-13 07:31:18","updated_at":"2016-07-13 07:31:18","deleted_at":null},{"id":84,"feed_id":55,"comment":"f1s2","user_id":1,"created_at":"2016-07-13 07:32:42","updated_at":"2016-07-13 07:32:42","deleted_at":null}]} Now it is returning the comments also. – Vikram Shaw Jul 13 '16 at 07:41
  • Works! Right? Comments are there – Mike Barwick Jul 13 '16 at 07:42
  • Ya, but the thing is it is returning in json format and when I'm returning at my home page(where feeds and comments are suppose to be displayed) there it is showing error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.comment_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`comment_id` = 83 and `users`.`comment_id` is not null limit 1) – Vikram Shaw Jul 13 '16 at 07:49
  • It's not returning json. It's returning an object. Remove all the users lines of code in the foreach. It'll work. Your relationship for users is wrong. Take what you learned here to set the user relationship up. – Mike Barwick Jul 13 '16 at 07:52
  • Hint, in your comment model, in user method, try this `return $this->hasOne('App\User', 'user_id', 'id'); }` – Mike Barwick Jul 13 '16 at 07:55
  • When it works, please accept answer AND vote up please! – Mike Barwick Jul 13 '16 at 07:55
  • Even after changing the relationship of user as you told it is showing error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`user_id` = 83 and `users`.`user_id` is not null limit 1). – Vikram Shaw Jul 13 '16 at 08:23
  • This is the for loop whic I'm using to show the comments @foreach($feed->comments as $comment)
    Image
    {{ $comment->user->first_name }} {{ $comment->created_at->diffForHumans() }} {{ $comment->feed->comment }}
    @endforeach
    – Vikram Shaw Jul 13 '16 at 08:24
  • In the `hasOne` which around "user_is" and "id". Put "id" first. – Mike Barwick Jul 13 '16 at 08:32
  • After replacing the position of 'user_id' and 'id'. It is showing this SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.feed_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`feed_id` = 1 and `users`.`feed_id` is not null limit 1) – Vikram Shaw Jul 13 '16 at 08:56
  • Not sure why it's giving you that error. Are you in the Comment model? Sounds like you're in the Feed model... – Mike Barwick Jul 13 '16 at 13:26
  • No I'm in comment model only. See this are the codes feed.blade.php http://laravel.io/bin/Lk0Yl . feedscontroller:- http://laravel.io/bin/wJzjQ user.php:- http://laravel.io/bin/qQPVW feed.php:- http://laravel.io/bin/0ev19 comment.php:- http://laravel.io/bin/7wv0v . Please do look the codes I know its frustrating for you to see all the codes again but thank you for helping. – Vikram Shaw Jul 13 '16 at 13:52
  • Well, does your Feed have a relationship to User? You're calling $feed->user, etc. – Mike Barwick Jul 13 '16 at 15:47
  • Also, on your Feed table, you should have an incrementing ID column...if "feed_id" is it, bad practice. Change to "id". – Mike Barwick Jul 13 '16 at 15:50
  • Yes Feed have a relationship with user. If I'm removing the comment loop from feed.blade.php then it is showing the feeds only with user name and with comment loop it is showing error but when I'm changing the relationship as you told in Feed then with or without comment loop it is showing error. And sorry I'm new to this coding n all so I changed that for better understanding of myself. – Vikram Shaw Jul 13 '16 at 18:23
  • Right now after changing the relationship it is showing this error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.feed_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`feed_id` is null and `users`.`feed_id` is not null) – Vikram Shaw Jul 13 '16 at 18:24
  • ^ it's going to cause problems in the future and make your life a living hell...don't create bad habits. Trust. :) – Mike Barwick Jul 13 '16 at 18:25
  • Thanks for the advice I'll keep in my mind. So what should we do to remove this error. – Vikram Shaw Jul 13 '16 at 18:26
  • Showing error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`user_id` is null and `users`.`user_id` is not null) with both the code which you told me to change – Vikram Shaw Jul 13 '16 at 18:34
  • Error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`user_id` is null and `users`.`user_id` is not null) – Vikram Shaw Jul 13 '16 at 18:40
  • Brain is pulsating lol I had an error, try this: `user() { return $this->hasMany('App\User', 'id', 'user_id'); }` – Mike Barwick Jul 13 '16 at 18:51
  • I've used user() { return $this->hasMany('App\User', 'id', 'user_id'); } and user() { return $this->hasMany('App\User', 'user_id', 'id'); } both showing the above errors – Vikram Shaw Jul 13 '16 at 18:54
  • Also, add "user" to `with`. Like so, `$feeds = Feed::with('comments', 'user')->get();` For testing purposes, just `return $feeds;` in your controller until we get the user object for feed. – Mike Barwick Jul 13 '16 at 18:56
  • After changing from hasMany to hasOne then also it is showing error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`user_id` = 83 and `users`.`user_id` is not null limit 1). Even interchanging the 'user_id' and 'id' – Vikram Shaw Jul 13 '16 at 18:58
  • Leave as `hasOne`. Tell me what `return $feeds;` returns when you add "user" to `with`. See my comment above. – Mike Barwick Jul 13 '16 at 19:00
  • Just looking at your controller method...mess...explains why some things are not working. I need to re-write the index. You didn't follow my code in answer. http://laravel.io/bin/fork/wJzjQ – Mike Barwick Jul 13 '16 at 19:02
  • To test, in FeedsController (index method) replace `return view('action.index', compact('feeds', 'blogs'));` with `return $feeds` so we can see result. – Mike Barwick Jul 13 '16 at 19:08
  • It is returning the object now. – Vikram Shaw Jul 13 '16 at 19:10
  • {"feed_id":55,"user_id":1,"feed_content":"First status","created_at":"2016-07-13 07:31:10","updated_at":"2016-07-13 07:31:10","comments":[{"id":82,"feed_id":55,"comment":"first comment","user_id":1,"created_at":"2016-07-13 07:31:18","updated_at":"2016-07-13 07:31:18","deleted_at":null},{"id":84,"feed_id":55,"comment":"f1s2","user_id":1,"created_at":"2016-07-13 07:32:42","updated_at":"2016-07-13 07:32:42","deleted_at":null}] – Vikram Shaw Jul 13 '16 at 19:16
  • "user":{"id":1,"email":"admin@admin.com","permissions":[],"last_login":"2016-07-13 18:09:51","first_name":"John","last_name":"Doe","created_at":"2016-06-13 05:55:08","updated_at":"2016-07-13 18:09:51","deleted_at":null,"bio":null,"gender":null,"dob":"0000-00-00","pic":"11zsHvWsNQ.jpg","country":"","state":"","city":"","address":"","postal":"","username":"admin"}}].. It is returning everything like feed, comment and whatever is there in user table – Vikram Shaw Jul 13 '16 at 19:17
  • Perfect. So now you foreach in your view should work, right? – Mike Barwick Jul 13 '16 at 19:20
  • Ok by seeing the result I guess it should be working. But how to show this in my home page. – Vikram Shaw Jul 13 '16 at 19:22
  • Make sure `return $feeds` is obviously changed back to `return view('action.index', compact('feeds', 'blogs'));`. This was just to make sure the object was correct... – Mike Barwick Jul 13 '16 at 19:28
  • The object are returning fine but if I'm changing return $feeds to return view('action.index', compact('feeds', 'blogs')); it is showing error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`user_id` = 83 and `users`.`user_id` is not null limit 1) – Vikram Shaw Jul 13 '16 at 19:31
  • This is all it is showing ErrorException in Connection.php line 662: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`user_id` = 83 and `users`.`user_id` is not null limit 1) (View: C:\wamp\www\newjosh\resources\views\action\partials\feed.blade.php) (View: C:\wamp\www\newjosh\resources\views\action\partials\feed.blade.php) – Vikram Shaw Jul 13 '16 at 19:35
  • Please Laravel Bin your current files: controller, feeds view, comment model, feed model. Thanks. – Mike Barwick Jul 13 '16 at 19:36
  • Feed model http://laravel.io/bin/QNMRd feedcontroller http://laravel.io/bin/6LKOV comment model http://laravel.io/bin/XyMRy feed balde http://laravel.io/bin/NkeRV – Vikram Shaw Jul 13 '16 at 19:40
  • After changing comment model getting this error ErrorException in Connection.php line 662: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'feeds.id' in 'where clause' (SQL: select * from `feeds` where `feeds`.`id` = 56 limit 1) (View: C:\wamp\www\newjosh\resources\views\action\partials\feed.blade.php) (View: C:\wamp\www\newjosh\resources\views\action\partials\feed.blade.php) – Vikram Shaw Jul 13 '16 at 19:47
  • Oh, you don't have a `id` column in your feeds table, right? – Mike Barwick Jul 13 '16 at 19:48
  • No instead of that I have feed_id – Vikram Shaw Jul 13 '16 at 19:50
  • What's this in your view? `{{ $comment->feed->comment }}`? Remove this and see if the error still exists. This doesn't make sense to me. I think it should be `{{ $comment->comment }}` – Mike Barwick Jul 13 '16 at 19:52
  • Thank you for all this. You really are a saviour. – Vikram Shaw Jul 13 '16 at 19:55
  • Now getting the output perfectly. – Vikram Shaw Jul 13 '16 at 19:56
  • Phew!! Finally!!! haha. Please accept answer and give it an up vote if you can too - for the extra hard work. :p – Mike Barwick Jul 13 '16 at 19:56
  • I'd spend a week going through Laracasts.com too...super helpful and will save you lots of time long term. Jefferey Way is a great teacher. – Mike Barwick Jul 13 '16 at 19:57
  • Definitely I'll give up vote for your hard work. Can you tell me what was the mistakes I did so that I'll try not to repeat them. – Vikram Shaw Jul 13 '16 at 19:59
  • No idea where to start with that. Just learn "relationships" and "eager loading" (i.e. the `with('comments', 'user')` stuff). – Mike Barwick Jul 13 '16 at 20:00
  • Ok thanks anyway. Any recommendation from where I should learn this and all. – Vikram Shaw Jul 13 '16 at 20:04
  • Learn from Laracasts.com. By far best tutorials (all video) to learn Laravel. Thanks for the answer accept...if you could vote up as well, I'd be grateful! – Mike Barwick Jul 13 '16 at 20:05
  • I tried to up vote but it is saying that since I'm new user and have reputation less that 15 so they will record the up vote but they will not display in public. – Vikram Shaw Jul 13 '16 at 20:07
  • No worries! As for tutorial, try this one: https://laracasts.com/series/laravel-5-from-scratch – Mike Barwick Jul 13 '16 at 20:07
  • Thanks for all this help. If you don't mind can I ask you one more thing. – Vikram Shaw Jul 13 '16 at 20:08
  • Right now my home page is working fine not to mention all because of you. In my home page feeds and blogs are showing but not according to the created time. First it is loading all the feeds then it is loading the blogs. I want the mixture of all according to time not like first feed and then blog. I have echoed like this only http://laravel.io/bin/ro48Q because of that it is showing like this. So can you tell me how to correct that. – Vikram Shaw Jul 13 '16 at 20:17
  • Hmm, that's a little more complex. I'd suggest making another question. – Mike Barwick Jul 13 '16 at 20:25
  • When/if you create a new question, post link here and I'll try and take a look. – Mike Barwick Jul 13 '16 at 20:28
  • Right now only I'll post within 15 mins – Vikram Shaw Jul 13 '16 at 20:30
  • This is the link:-- http://stackoverflow.com/questions/38361471/displaying-feeds-and-blogs-according-to-the-created-time – Vikram Shaw Jul 13 '16 at 20:57