The code runs fine without the #foreach statement. When it's added I get the following error:
Undefined variable: articles (View: C:\laravel\laravel\resources\views\about.blade.php)
$articles is undefined.
Make the variable optional in the blade template. Replace {{ $articles }} with {{ $articles ?? '' }}
When I add the ?? '' it creates the error:
Facade\Ignition\Exceptions\ViewException
Invalid argument supplied for foreach()
Here is the complete code for the more daring:
https://github.com/matthoek/Articles
This is my view:
<? if (is_array($articles) || is_object($articles)) ?>
{
#foreach ($articles ?? '' as $article)
{
<li class = "first">
<h3>{{ $article->title}}</h3>
<p>{{ $article->excerpt }}</p>
</li>
#endforeach
}
}
</ul>
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Article;
class ArticlesController extends Controller
{
public function index()
{
$articles = App/Article::latest()->get();
//$articles = Review::all();
//$article = Review::all();
return view('articles.index',['articles'=>$articles]);
//return view('articles.index', ['articles' => $articles]);
}
public function show($id)
{
$article = App/Article::find($id);
//return view('articles.show', ['article' => $article]);
return view('articles.show')->with('article');
}
public function create()
{
return view('articles.create');
}
public function store()
{
//validation
//clean up
$article = new Article();
$article->title = request('title');
$article->excerpt = request('excerpt');
$article->body = request('body');
$article->save();
return redirect('/articles');
}
public function edit()
{
return view('articles.edit');
}
}
This is the section of my routes file web.php
Route::group(['middleware' => ['web']], function ()
{
Route::get('/about', function () {
$article = App\Article::latest()->get();
return view('about', compact('about', 'articles'));
//return $article;
});
}
I have changed the section of the routes file to the following but it did not seem to work.
return view('about')->with(['article'=> $article]);
I have made sure the following was in my app/Http/Kernel.php in middlewareGroups property for web
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
I have changed the foreach loop to an each loop and I get the same error on the line:
<h3>{{article->title}}</h3>
Let me know if I should post more code.
In your routes:
Route::get('/about', function () {
$articles = App\Article::latest()->get();
return view('about', compact('about', 'articles'));
});
It will return a collection, you can just loop it:
<ul>
#foreach ($articles as $article)
<li class = "first">
<h3>{{ $article->title}}</h3>
<p>{{ $article->excerpt }}</p>
</li>
#endforeach
</ul>
Update your view
<? if (is_array($articles) || is_object($articles)) ?>
{
#foreach($articles as $article)
<li class = "first">
<h3>{{ $article->title}}</h3>
<p>{{ $article->excerpt }}</p>
</li>
#endforeach
}
</ul>
the error is in you foreach loop: https://www.php.net/manual/en/control-structures.foreach.php
Related
Sorry, I'm new to developing on Laravel. I'm trying to show info contained in the database on my page. But it can't find the variable holding all the data. I can see the info in Tinker, but i can't seem to deplay is.
I posted some pictures so you can have a look. I'd love to hear your feedback.
Images: https://imgur.com/a/zLSqSDG
Code:
Route:
<?php
Route::get('/', function () {
return view('index');
});
Route::resource('complaints', 'ComplaintController');
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Complaint;
class ComplaintController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$complaints = Complaint::all();
return view('index', compact('complaints'));
}
Blade:
#extends('layout')
#section('title','Welcome')
#section('content')
{{-- #foreach ($complaints as $complaint)
<h1>{{ $complaint->title }}</h1>
<p>{{ $complaint->body }}</p>
#endforeach --}}
{{ $complaints }}
#endsection
You are not routing to the correct function in your controller. Try this
Route::resource('complaints', 'ComplaintController#index');
Try it with another syntax like below:
public function index() {
$complaints = Complaint::all();
return view('index')->with(compact('complaints'));
}
or
public function index() {
$complaints = Complaint::all();
return view('index')->with('complaints', $complaints);
}
As #amirhosseindz said
When you're visiting this url : http://127.0.0.1:8000/complaints it will work because you're hitting
Route::resource('complaints', 'ComplaintController');
But when you visit this url : http://127.0.0.1:8000
you're hitting this action:
Route::get('/', function () {
return view('index');
});
where $complaints doesn't exists
You should try this:
Your Controller
public function index() {
$complaints = Complaint::all();
return view('index',compact('complaints'));
}
Your View (index.blade.php)
#extends('layout')
#section('title','Welcome')
#section('content')
#if(isset($complaints))
#foreach ($complaints as $complaint)
<h1>{{ $complaint->title }}</h1>
<p>{{ $complaint->body }}</p>
#endforeach
#endif
#endsection
Okay,
So I can't figure this one out.
Eloquent model is new to me.
I'm trying to fetch comments for specific posts.
This is my post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function post()
{
return $this->belongsTo('App\Post');
}
}
Routes:
public function getDashboard(){
$posts = Post::orderBy('created_at', 'desc')->get(); // MySQL ORDER BY
$comments = Comment::orderBy('created_at', 'desc')->get();
return view('dashboard', ['posts' => $posts], ['comments' => $comments]);
}
($comments might be unnecessary?)
View:
#foreach($posts as $post)
<article class="post" data-postid=" {{ $post->id }} ">
<p>{{ $post->body }}</p>
<div class="info">
Posted by {{$post->user->first_name}} on {{ $post->created_at }}
</div>
</article>
I tried to loop through the comments using:
#while($comments->post_id = $post->id)
<p>{{$comments->body}}</p>
#endwhile
I got an error message "Undefined property: Illuminate\Database\Eloquent\Collection::$body" even though the comments table have a column named "body".
#foreach($post->comments as $comment)
Is what you want. You can use eager loading in the query to speed this up as well:
Post::with('comments')->orderBy('created_at', 'desc')->get()
You code with create multiple queries because of $post->user->first_name. For example, if you have 70 posts, your code will create 72 query which is awful.
It's much better to use eager loading to load posts with comments and users. This code will create just 3 queries:
Post::orderBy('created_at', 'desc')
->with(['user', 'comments' => function ($q) {
$q->orderBy('created_at', 'desc');
}])->get();
And then itarate over collection:
#foreach ($posts as $post) {
<article class="post" data-postid=" {{ $post->id }} ">
....
#foreach ($post->comments as $comment) {
$comment->content;
}
}
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 bulid website that user can make a post and comment on it. The comment can have many file. Create comment and file work fine but when show the post, that just show post and comment, not with comment's file.
//Post.php
public function commentsPost()
{
return $this->hasMany('App\commentPost');
}
//CommentPost.php
public function post()
{
return $this->belongsTo('App\Post');
}
public function filesPost()
{
return $this->hasMany('App\FilePost');
}
//FilePost.php
public function commentsPost()
{
return $this->belongsTo('App\CommentPost');
}
This my CommentController.php
public function show($id)
{
$post = Post::findOrFail($id);
if ($post != null) {
return view('post.show', compact('post'));
} else {
return redirect('/')->with('error', 'This post does not exist.');
}
}
And show.blade.php
#foreach($post->commentsPost as $comment)
<h2>{{ $comment->message }} by {{ $comment->user->name }}</h2>
#foreach($comment->filesPost->all() as $file)
<h5>{{ $file->filename }}</h5>
#endforeach
#endforeach
I use dd($post->commentsPost->filesPost->all()); and error Undefined property: Illuminate\Database\Eloquent\Collection::$filesPost
How to show the comment also the file? I use Laravel 5
try this
#foreach($post->commentsPost as $comment)
<h2>{{ $comment->message }} by {{ $comment->user->name }}</h2>
#foreach($comment->filesPost() as $file)
<h5>{{ $file->filename }}</h5>
#endforeach
#endforeach
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]);
}