Get users name from table Laravel - php

I want to display user name from users table. I get article information for example {{$article->title}}
but i doesnt get users info.
Model Article
protected $fillable = ['title','slug','description_short','description','image_path','meta_title',
'meta_description','meta_keyword','published', 'created_by', 'modified_by','author_id'];
public function user(){
return $this->belongsTo(User::class);
}
Model User
protected $fillable = [
'id', 'name', 'email', 'password', 'role_id'
];
public function articles(){
return $this->hasMany('App\Article');
}
index.blade.php
#forelse ($articles as $article)
<tr>
#foreach($article as $userss)
<?php var_dump($userss) ?>
<div class="display-commentttt">
#if (isset($userss->users->name))
<?php var_dump($userss->users->name); ?>
<div class="user-login">{{ $userss->user->name }}
</div>
#elseif (isset($userss->users->id))
<?php var_dump($userss->users->name); ?>
<div class="user-login">{{ $userss->users->id }}
</div>
#endif
#endforeach
<td>{{$article->title}}</td>
<td>{{$article->published}}</td>
#endforelse
In my article Controler
public function index(){
return view('admin.articles.index',[
'articles' => Article::with(['user'])->orderBy('created_at', 'desc')->paginate(10),
]);
}

This is easily possible by Eloquent. In your Article model rename your function users() to user();
public function user(){
return $this->belongsTo(User::class);
}
then go to your controller's method and get article data using following method
public function view_articles(){
//you must have to import Article model at the top
$articles = Article::with(['user'])->get();
dd($articles); //this will show response.
return view('view_file')->with(compact('articles'));
}
//inside your view file
#foreach ($articles as $article)
<tr>
#foreach($article as $userss)
<td>{{$article->title}}</td>
<td>{{$article->published}}</td>
<td>{{$article->user->name}}</td>
#endforeach
#endforeach

Related

Many to Many Relationship return trying to get property 'books' of non-object

I am trying to displaying the book a user has favorited, so I think many to many relationships will solve it. So I have 3 tables
Users Table
Books Table
Favorite Table
The Favorite table is the pivot table
Schema::create('favorites', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('book_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
In the User Model
public function favorites(){
return $this->hasMany(Favorite::class);
}
In the Book Model
public function favorites()
{
return $this->hasMany(Favorite::class);
}
In my Favorite Model
public function book ()
{
return $this->belongsTo(Book::class);
}
I was able to save to Favorite Column like this
public function favorite($id)
{
Favorite::create([
'book_id' => $id,
'user_id' => Auth::id()
]);
Session::flash('success', "You Favorite a Book");
return redirect()->back();
}
But I am trying to show the Books Favorited
public function mylibrary(){
$user = Auth::user()->books;
// dd($user);
return view('library', compact('user'));
}
In my view, I have this
#foreach($user->books as $mybook)
...
<div class="clearfix"></div>
<p class="authorone">{{ $mybook->author->name }}</p>
<h1 class="book-title">{ $mybook -> title }}</h1>
</div>
#endforeach
You are passing Auth::user()->books to your view, not Auth::user(). You are not passing the User.
In the view you are then trying to use that value as an object:
#foreach ($user->books as $mybook)
Auth::user()->books is most likely returning null since it is not a relation method or an attribute (most likely).
You probably want to pass the User to your view:
view(..., ['user' => Auth::user()]);
Then you would want to access the correct dynamic property for the relationship you want since you aren't showing a books relationship on User.
Your model relationships could use a better setup. There is no Many to Many setup here and you don't need to define a model for the pivot, you are actually avoiding the Many to Many by doing this.
Models:
class User
{
public function books()
{
return $this->belongsToMany(Book::class, 'favorites');
}
}
class Book
{
public function users()
{
return $this->belongsToMany(User::class, 'favorites');
}
}
Controller:
public function favorite($id)
{
Auth::user()->books()->attach($id);
...
}
public function mylibrary()
{
$user = Auth::user()->load('books.author');
return view('library', compact('user'));
}
View:
#foreach($user->books as $mybook)
...
<div class="clearfix"></div>
<p class="authorone">{{ $mybook->author->name }}</p>
<h1 class="book-title">{{ $mybook->title }}</h1>
</div>
#endforeach
I was able to solve it this way
My view
#forelse ($user->favorites as $mybook)
<p class="authorone">{{ $mybook ->book->author-> name }}</p>
<h1 class="book-title">{{ $mybook ->book-> name }}</h1>
#empty
<h2>You haven't Favorited any book</h2>
<div class="text-center">
Return To
</div>
#endforelse
I added this to my user model
public function favorites(){
return $this->hasMany(Favorite::class);
}
public function books()
{
return $this->belongsToMany(Book::class);
}
My controller
public function mylibrary(){
return view('library', ['user' => Auth::user()]);
}

Laravel Eloquent BelongTo Model Access fails

I am trying to get data by using Laravel Eloquent HasMany (reverse) relationship but I am not getting access. Whenever I try, it shows Trying to get property 'name' of non-object
I have two models. Category and Article. Category hasMany Articles. Here are the models:
Category Model
protected $fillable = [
'user_id', 'name',
];
public function articles()
{
return $this->hasMany('App\Models\Article');
}
Article Model
protected $fillable = [
'user_id', 'headline', 'summary', 'body', 'status', 'cover_image', 'image_caption', 'image_credit', 'cover_video', 'video_caption', 'video_credit', 'category', 'meta', 'tags',
];
public function category()
{
return $this->belongsTo('App\Models\Category','category');
}
Article Controller
public function pendingposts()
{
$user = Auth::user();
$articles = Article::all();
return view('admin.article.pending-posts')->with(['user' => $user, 'articles' => $articles]);
}
View Blade (admin.article.pending-posts)
#foreach($articles->where('status', 'submitted')->sortByDesc('updated_at') as $article)
<tr>
<td >{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
#endforeach
here in blade, I can not access category through eloquent BelongsTo feature and I am not getting the reason behind getting the message:
ErrorException (E_ERROR)
Trying to get property 'name' of non-object (View:
C:\xampp\htdocs\joliadmin\resources\views\admin\article\pending-posts.blade.php)
You should try this:
public function pendingposts()
{
$user = Auth::user();
$articles = Article::with('category')
->where('status', 'submitted')
->sortByDesc('updated_at')
->get();
return view('admin.article.pending-posts')->with(compact('user', 'articles'));
}
#foreach($articles as $article)
<tr>
<td>{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
#endforeach
Updated Answer
Category Model
protected $fillable = [
'user_id', 'name',
];
public function article()
{
return $this->hasMany('App\Models\Article');
}
it worked after changing 'Article' tables 'category' column in 'category_id'. Thanks for helping.

Laravel - Multiple Controllers within a View

I'm trying to code a simple social media page. The show view should display a post with all the comments for that particular post listed below.
I've tried a couple different approaches with no luck, this is the approach I feel like I might be closet to success with, any suggestions?
I can provide other extracts of code if you think the problem lies elsewhere but I think my problem lies within these 4 files.
web.php
Route::resource('post', 'PostController');
Route::resource('post', 'CommentController');
show.blade.php
<h1>{{$post->title}}</h1>
<p>Description: {{$post->description}}</p>
<h3>Comments</h3>
<ul>
#foreach ($comments as $comment)
<li>
User: {{$comments->user_name}} <br>
Comment: {{$comments->comment}} <br>
</li><br>
#endforeach
</ul>
PostController.php
public function show($id)
{
$post= Post::find($id);
return view('post.show')->with('post', $post);
}
CommentController.php
public function show($id)
{
$comments= Comment::find($id);
return view('post.show')->with('comments', $comments);
}
EDIT 1
Post.php
class Post extends Model
{
protected $fillable = ['title', 'description'];
function user() {
return $this->belongsTo('App\User');
}
function comment() {
return $this->hasMany('App\Comment');
}
}
firstly set the relationship between Post and Comment Model
In Post Model
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}
In Comment Model
class Comment extends Model
{
public function post(){
return $this->belongsTo(Post::class);
}
}
Post Controller
public function show($id)
{
$post= Post::find($id);
return view('post.show')->with('post', $post);
}
Write in the blade file
<h1>{{$post->title}}</h1>
<p>Description: {{$post->description}}</p>
<h3>Comments</h3>
<ul>
#foreach ($post->comments as $comment) //get all the comments related to this post
<li>
User: {{$comment->user_name}} <br>
Comment: {{$comment->comment}} <br>
</li><br>
#endforeach
</ul>
You can get both data by make relations between your models
I think in your two models the relation would be like that,
Post Model
namespace App\Post;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}
Comment Model:
namespace App\Comment;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post(){
return $this->belongsTo(Post::class);
}
}
so if you want to return the data to view then,
PostController.php
public function show($id)
{
$post= Post::with('comments')->find($id);
$data = [
'post' => $post,
'comments' => $post->comments,
];
return view('post.show', $data);
}
CommentController.php
public function show($id)
{
$comments= Comment::with('post')->find($id);
$data = [
'post' => $comments->post,
'comments' => $comments,
];
return view('post.show' , $data);
}
For more details: https://laravel.com/docs/5.7/eloquent

Laravel 5.1 - Showing Comments on Specific Page

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]);
}

Trying to get column data from pivot table laravel

Hi I'm trying to output a certain column from my pivot table. To show you what I have tried, I will first show you my models (my pivot tables are ordertasks and tagtasks):
Task table:
class Task extends \Eloquent {
// Add your validation rules here
public static $rules = [
// 'title' => 'required'
];
// Don't forget to fill this array
protected $fillable = ['task_name','task_description','hour','difficulty'];
public function ordertask()
{
//oneToMany
return $this->hasMany('Ordertask', 'id_task', 'id');
}
public function tagtask()
{
//oneToMany
return $this->hasMany('Tagtask', 'id_task', 'id');
}
}
Tagtask table:
<?php
class Tagtask extends \Eloquent {
protected $fillable = ['id_tag','id_task'];
public function task()
{
//manyToOne
return $this->belongsTo('Task', 'id_task', 'id');
//return $this->belongsTo('Task');
}
public function tag()
{
//manyToOne
return $this->belongsTo('Tag', 'id_tag', 'id');
}
}
Ordertask table:
<?php
class Ordertask extends \Eloquent {
// Add your validation rules here
public static $rules = [
// 'title' => 'required'
];
// Don't forget to fill this array
protected $fillable = ['id_order','id_task', 'hour', 'hourprice','id_user', 'createdBy'];
public function user()
{
//manyToOne
return $this->belongsTo('User', 'id_user', 'id');
//return $this->belongsTo('User');
}
public function task()
{
//manyToOne
return $this->belongsTo('Task', 'id_task', 'id');
//return $this->belongsTo('Task');
}
}
Here is my TaskController.php with the following piece of code:
public function index()
{
$Tasks=Task::with('tagtask','ordertask')->get();
return View::make('user.tasks.index', compact('Tasks'));
}
Okay now comes the part where I want to show $Task->ordertask['id_user'] on my browser with the following piece of code:
#if (count($Tasks))
<ul>
#foreach($Tasks as $Task)
<div class="row">
<div class="col-md-3">
<li>
{{--as a third parameter we need to pass in the id of task, because it needs to be fed to
our actual user.task.edit route. --}}
{{link_to_route('user.tasks.edit', $Task['task_name'], array($Task->id))}}
</li>
</div>
<div class="col-md-3">
<li>
{{$Task->ordertask['id_user']}}
</li>
</div>
<div class="col-md-3">
<li>
{{$Task['task_hour']}}
</li>
</div>
<div class="col-md-3">
<li>
{{Form::open(array('route'=>array('user.tasks.destroy',$Task->id),
'method'=>'delete','class'=>'destroy'))}}
{{Form::submit('Delete')}}
{{Form::close()}}
</li>
</div>
</div>
#endforeach
</ul>
#endif
Unfortunately that doesn't work because I get the following error:
Undefined index: id_user
Instead of:
{{$Task->ordertask['id_user']}}
I have also tried this just to see what output it gave me:
{{$Task->ordertask}}
Which gave me the following output:
[{"id":5,"id_order":2,"id_task":1,"hour":63,"hourprice":15,"id_user":5,"createdBy":4,"created_at":"2014-10-13 10:21:33","updated_at":"2014-10-13 10:21:33"}]
So gladly I want to output id_user from the ordertask table. Gladly I'm waiting on your answer. Anyway thanks for your response.
One Task can have many order tasks, so to display users instead of
{{$Task->ordertask['id_user']}}
You should use:
#foreach ($Task->ordertask as $ot)
{{ $ot->id_user }}
#endforeach

Categories