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">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</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
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.
Related
my relational database image
{{ \App\User::where('id', $comment->user_id)->value('name') }}
if I use the code above
name user show in all post
my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Komen extends Model
{
protected $table='komentar_post';
}
my controller
public function index()
{
$post=Post::all();
$comment=Komen::all();
$user=User::all();
// dd($id);
return view('home',compact('post','comment','user'));
}
my view
#foreach($comments as $cm)
{{ \App\User::where('id', $cm->user_id)->value('name') }}
#endforeach
what the corect query i must use
You need to create relationship in your Komen model. It's something like this:
class Komen extends Model
{
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
Then, you can Eager Load that relationship when fetching the Komen.
PostsController.php
public function show(Post $post)
{
$comments = $post->comments()->with('user')->paginate();
return view('posts.show', compact('comments'));
}
Then, you can access user data when displaying each comments:
posts/show.blade.php
#foreach($comments as $comment)
{{ $comment->user->name }}
#endforeach
{!! $comments->links() !!}
Update
Ok, if you need to displaying comments when you're displaying all posts, first you need to setup the relationship!
Post.php
class Post extends Model
{
public function comments()
{
return $this->hasMany(Komen::class, 'post_id');
}
}
Komen.php
class Komen extends Model
{
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
PostsController.php
public function index()
{
$posts = Post::with('comments.user')->paginate();
return view('home', compact('posts'));
}
home.blade.php
#foreach($posts as $post)
#foreach($post->comments as $comment)
{{ $comment->user->name }}
#endforeach
#endforeach
{!! $posts->links() !!}
I'm using a custom encryption trait on my Journal model. I didn't create this code and vaguely understand how it works, but the original code can be found here on this Laracast forum post.
Encryption.php
<?php
namespace App;
use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable)) {
$value = Crypt::decrypt($value);
return $value;
}
return $value;
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
Journal.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Journal extends Model
{
use Encryptable;
protected $encryptable = [
'content'
];
protected $fillable = ['content','user_id'];
}
I'm getting two problems:
Call to a member function toRfc822String() on null (View: /Applications/MAMP/htdocs/thought-records/resources/views/journal/index.blade.php)
When I remove toRfc822String() from my blade file it throws this error: The payload is invalid.
Here is the index.blade.php
<div class="card-body">
#if($entries->isEmpty())
<p>There is nothing here!</p>
#else
#foreach($entries as $entry)
<h3>{{ $entry->created_at }}</h3>
<div v-html="markdown('{{ htmlentities($entry->content) }}')"> </div>
<hr>
#endforeach
#endif
</div>
The getAttribute method has to return something. Your method returns void. Every attribute you try to access via the dynamic property, $model->attribute, will be null because of this.
I'm trying to show the name of user alongside with their comment, as Tour does not belong to a user, I'm facing [user] issue here. Failed to pass the user information with comments. In my code, I can show only comments that belong to tour but not the users who comment.
Tour
class Tour extends Model{
protected $table = 'tour';
public function disTour()
{
return $this->hasMany('App\District');
}
public function review()
{
return $this->hasMany(TourReview::class);
}
TourReview Model
class TourReview extends Model{
protected $table = 'tour_review';
public function tour()
{
return $this->belongsTo('App\Tour');
}
public function user()
{
return $this->belongsTo('App\Users');
}
Users Model
class Users extends Model{
protected $table = 'users';
public function userBlogs()
{
return $this->hasMany('App\Blog');
}
public function tourReview()
{
return $this->hasMany('App\TourReview');
}
Controller
public function singleDetails($id)
{
$tour = Tour::find($id);
$comments = Tour::find($id)->review;
$users = TourReview::with('user')->where('id', $comments->pluck('id'))->get();
foreach ($users as $user){
dd($user);
}
//$blogs = Blog::with('images')->where('user_id', $user_id)->paginate(10);
dd($comments);
return view('Tours.single_tour')
->with(compact('tour', 'comments'));
}
Blade View
#foreach($comments as $comment)
<div class="review_strip_single">
<img src="{{asset('wanna show commented user photo')}}" height="78" width="78" alt="Image" class="img-circle">
<small> - {{$comment->created_at->format('d M Y')}} -</small>
<h4>{{wanna show user name}}</h4>
<p> {{$comment->tourreview_desc}} </p>
</div>
#endforeach
you can do nested query in controller
public function singleDetails($id)
{
$tour = Tour::with(['review.user'])->find($id);
return view('Tours.single_tour')
->with(compact('tour'));
or if you want only comments
$comments = Review::with('user')->whereHas('tour', function ($q)use($id){
$q->where('id', $id);
});
return view('Tours.single_tour')
->with(compact('comments'));
}
Blade View
#foreach($tour->comments as $comment)
<div class="review_strip_single">
<img src="{{asset('wanna show commented user photo')}}" height="78" width="78" alt="Image" class="img-circle">
<small> - {{$comment->created_at->format('d M Y')}} -</small>
<h4>{{$comment->user->name}}</h4>
<p> {{$comment->tourreview_desc}} </p>
</div>
#endforeach
or
#foreach($comments as $comment)
<div class="review_strip_single">
<img src="{{asset('wanna show commented user photo')}}" height="78" width="78" alt="Image" class="img-circle">
<small> - {{$comment->created_at->format('d M Y')}} -</small>
<h4>{{$comment->user->name}}</h4>
<p> {{$comment->tourreview_desc}} </p>
</div>
#endforeach
I have created a model called company and projects, I need to show projects under a company. The company is showing fine, but when I added a project relation to the model, it displays an error. I am a newbie to Laravel.
Undefined constant 'App\App\projects' (View:
C:\xampp\htdocs\testdrive\resources\views\companies\show.blade.php)
C:\xampp\htdocs\testdrive\app\company.php
Model
use Illuminate\Database\Eloquent\Model;
class company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User);
}
public function projects()
{
return $this->hasMany(App\projects);
}
}
show.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<!-- Jumbotron -->
<div class="jumbotron">
<h1>{{$company->name}}</h1>
<p class="lead">{{$company->description}}</p>
</div>
<!-- Example row of columns -->
<div class="row">
#foreach($company->projects as $projects)
<div class="col-lg-4">
<h2>{{$projects->name}}</h2>
<p class="text-danger">{{$projects->description}} </p>
<p>
<a class="btn btn-primary" href="/projects/{{$projects->id}}" role="button">View Project</a>
</p>
</div>
#endforeach
</div>
</div>
#endsection
You've got a typo! namespaces should be strings:
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\projects');
}
You are missing class keyword in your model
class company extends Model
{
//
protected $fillable=[
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User::class);
}
public function projects()
{
return $this->hasMany(App\projects::class);
}
}
Hope this helps
Either pass class of the model or it's namespace within questions
public function user()
{
return $this->belongsTo(App\User::class); //or $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany(App\Project::class);
}
Aside from using quotes to reference the model as mentioned above.
It might also be necessary to define the namespace of your class.
Sidenote: it's also a Laravel naming convention to use PascalCase for classnames (ie. Company, WetCamel, FooBarClass)
namespace App\Company;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\Projects');
}
}
Use '' this to call the model.
Correct your syntax as:
public function projects()
{
return $this->hasMany('App\projects');
}
I have created registration form using Laravel, Form is working well, Validations are also working well but without validation error, when I try to save data, it redirects to "Whoops, looks like something went wrong." can someone please help me to find this error. thank you.
Form:
{{ Form::open(array('url'=>"create-account")) }}
<p>
{{ Form::text('user_name', '', array('placeholder'=>"User Name")) }}
#if($errors->has('user_name'))
<label> {{ $errors->first('user_name') }} </label>
#endif
</p>
<p>
{{ Form::text('user_email', '', array('placeholder'=>"User Email")) }}
#if($errors->has('user_email'))
{{ $errors->first('user_email') }}
#endif
</p>
<p>
{{ Form::password('user_password', array('placeholder'=>"User Password")) }}
#if($errors->has('user_password'))
{{ $errors->first('user_password') }}
#endif
</p>
<p>{{ Form::submit('Register') }}</p>
{{ Form::close() }}
And Controller has this code:
class StaffController extends BaseController {
public function getAccount() {
return View::make('staff.account');
}
public function postAccount() {
$input = Input::all();
$rules = array(
'user_name' => 'required|min:3|max:20|unique:users',
'user_email' => 'required|email|max:50|unique:users',
'user_password' => 'required|min:5'
);
$validate = Validator::make($input, $rules);
if ($validate->fails()) {
return Redirect::to('create-account')
->withErrors($validate);
} else {
$user = new User();
$user->user_name = $input['user_name'];
$user->user_email = $input['user_email'];
$user->user_password = Hash::make($input['user_password']);
$user->save();
return Redirect::to('login')
->with('global', 'Your account has been created, please login');
}
}
}
Model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
//protected $hidden = array('password', 'remember_token');
protected $hidden = array('user_password');
}
DB table has fields:
Table name: users
Fields:
user_id int(11)
user_name varchar(20)
user_email varchar(50)
user_password varchar(60)
status
Routes:
Route::get('/','HomeController#getIndex');
Route::get('login','HomeController#getIndex');
Route::post('login','HomeController#postLogin');
Route::get('create-account', 'StaffController#getAccount');
Route::post('create-account', 'StaffController#postAccount');