This is the code from CategoriesController:
public function index()
{
$categories = Category::all();
return view('/home', compact('categories'));
}
And this is the code that I'm writing to the home.blade.php
#foreach($categories as $cat)
#endforeach
And then in home.blade.php
I'm getting this error: Undefined variable: categories
Why this happening ? Everything works fine with Articles but not categories and the code is the same.
Home.blade.php
#extends('app')
#section('content')
<div class="col-md-4 pull-right">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Categories</h3>
</div>
<div class="panel-body">
#foreach($categories as $cat)
<div class="col-lg-6">
<ul class="list-unstyled">
<li>News
</li>
</ul>
</div>
#endforeach
</div>
</div>
</div>
#if(count($articles))
#foreach($articles as $article)
<div class="panel panel-default col-md-8">
<div class="panel-heading">
<h3>{{ $article->title }}</h3>
<small>posted by {{ $article->author->name }} {{ $article->created_at }}</small>
</div>
<div class="panel-body">
{!! str_limit($article->body, 1000) !!}
<hr>
Read More
</div>
</div>
#endforeach
#else
<h1>No articles at the moment.</h1>
#endif
<br>
{!! $articles->render() !!}
#stop
You have two routes
Route::get('/home', 'ArticlesController#index');
Route::get('/home', 'CategoriesController#index');
Which means when you visit /home, only ArticlesController#index is fired, not both.
This means that the $categories variable used in the view is not populated because your index() method in CategoriesController is intended to do this but is never called.
Therefore you need to do something like this
Route::get('/home', 'HomeController#index');
public function index()
{
$categories = Category::all();
$articles = Article::all();
return view('/home', compact('articles', 'categories'));
}
try to use
return View::make('/home')->with(compact('categories'));
instead of
return view('/home', compact('categories'));
I insert this in the top of my #foreach
<?php
use App\models\PersonalContact;
$data = PersonalContact::all();
?>
or this before #foreach add #if statement like this
#if (count($data) > 0)
#foreach ($data as $bloginfo)
<tr role="row" class="odd">
<td class="sorting_1">{{$bloginfo->name}}</td>
<td>{{$bloginfo->description}}</td>
<td>{{$bloginfo->email}}</td>
<td>{{$bloginfo->phone}}</td>
<td><img src="{{url('images/'.$bloginfo->image)}}" alt="" width="100px" height="100px"></td>
<td><i class="fas fa-edit"></i>Add | <i class="fas fa-edit"></i>Edit | <a class="btn btn-app"><i class="fas fa-edit"></i>Delete</a></td>
</tr>
#endforeach
#endif
return view('/home', compact('categories'));
The problem was $categories on compact method, you must use like a string
Related
I want to display multiple product image from database with eager loading, and when i tried to displaying it, console said localhost:8000/storage/ 404 not found. Any ideas how to solve this? this is my first time using eager loading & relationship on Laravel. Thank you!
Here is my controller :
public function homeProduct(){
$products = Product::with('productCategory')->get();
$images = Product::with('productImage')->get();
return view('home.index', compact('products', 'images'));
}
Product Model :
public function productImage()
{
return $this->hasMany(ProductImage::class, 'product_id', 'id');
}
Product Image Model :
public function product()
{
return $this->belongsTo(Product::class, 'id');
}
Here are the index.blade.php View :
#foreach ($products as $p)
<div class="col-lg-6 col-12">
<div class="portfolio-thumb mb-5" data-aos="fade-up">
<div id="yoreBeans" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
#foreach ($images as $key => $image)
<div class="carousel-item {{ $key == 0 ? 'active' : '' }}">
<a href="{{ asset('storage/'.$image->path) }}" class="image-popup">
<img src="{{ asset('storage/'.$image->path) }}" class="img-fluid portfolio-image" alt="">
</a>
</div>
#endforeach
</div>
</div>
<div class="portfolio-info">
<h3 class="text-black">{{ $p->name }}</h3>
<h4 class="text-danger">{{ $p->productCategory->name }}</h4>
</div>
</div>
</div>
#endforeach
Your method $images = Product::with('productImage')->get(); will also return Product objects with images.
What you exactly want is to eager load both realtions and then reference it at the same time:
public function homeProduct(){
$products = Product::with(['productCategory', 'productImage'])->get();
return view('home.index', compact('products'));
}
And your view like this:
#foreach ($products as $p)
<div class="col-lg-6 col-12">
<div class="portfolio-thumb mb-5" data-aos="fade-up">
<div id="yoreBeans" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<!-- // this line changed --->
#foreach ($p->productImage as $key => $image)
<div class="carousel-item {{ $key == 0 ? 'active' : '' }}">
<a href="{{ asset('storage/'.$image->path) }}" class="image-popup">
<img src="{{ asset('storage/'.$image->path) }}" class="img-fluid portfolio-image" alt="">
</a>
</div>
#endforeach
</div>
</div>
<div class="portfolio-info">
<h3 class="text-black">{{ $p->name }}</h3>
<h4 class="text-danger">{{ $p->productCategory->name }}</h4>
</div>
</div>
</div>
#endforeach
I want to go to specific page after click show button but after click show will get this error Undefined offset: 1
web.php
Route::get('/product/{id}', 'ProductController#show')->name('product.show');
ProductController.php
public function show($id)
{
$product = Product::find($id);
return view('product.show')->with(compact('product'));
}
home.blade.php
<div class="row">
#foreach($products as $product)
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img class="card-img-top" src="http://placehold.it/700x400" alt="">
<div class="card-body">
<h4 class="card-title">
{{ $product->name }}
</h4>
<h5>{{ $product->price }}</h5>
<p class="card-text">{{ $product->description }}</p>
<td><a class="btn btn-primary" href="{{ route('product.show', $product->id ) }}">Show</a></td>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
#endforeach
</div>
Your are doing wrong in blade file. Note here php array start from 0. So array is [0,1,2,3] and database id is start from 1.
this is the correct link
{{ route('product.show', ['Product' => $product->id]) }}
You have to use like below code
{{ route('product.show', ['id' => $product->id]) }}
return view('product.show', compact('product'));
And in your show.blade.php you have to use like below
{{$product->id}} or {{$product->name}} //etc //But not use foorloop
The find method will return only one item. You can't use the loop on it.
Try the following code.
web.php
Route::get('/product/{product}', 'ProductController#show')->name('product.show');
ProductController.php
public function show(Product $product)
{
return view('product.show')->with(compact('product'));
}
home.blade.php
<div class="row">
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img class="card-img-top" src="http://placehold.it/700x400" alt="">
<div class="card-body">
<h4 class="card-title">
{{ $product->name }}
</h4>
<h5>{{ $product->price }}</h5>
<p class="card-text">{{ $product->description }}</p>
<td><a class="btn btn-primary" href="{{ route('product.show', $product->id ) }}">Show</a></td>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
</div>
you are in wrong blade
you are returning product.show blade in your controller:
return view('product.show')->with(compact('product'));
but you put home.blade code!!!
put the right blade code
show.php: Why not try it $_ Get["id"]
i want to create some CMS project with the laravel, when the user trying to click the categories, the app will show the post that only shows the category that user clicked. When the user click the categories, the app says error Bad Method Call. What should i do? Any help will be appreciated.
Here's the code from web.php
<?php
use App\Http\Controllers\Blog\PostsController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'WelcomeController#index')->name('welcome');
Route::get('blog/posts/{post}', [PostsController::class, 'show'])->name('blog.show');
Route::get('blog/categories/{category}', [PostsController::class, 'category'])->name('blog.category');
Route::get('blog/tags/{tag}', [PostsController::class, 'tag'])->name('blog.tag');
Auth::routes();
Route::middleware(['auth'])->group(function () {
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('categories', 'CategoriesController');
Route::resource('posts','PostsController');
Route::resource('tags','TagsController');
Route::get('trashed-posts','PostsController#trashed')->name('trashed-posts.index');
Route::put('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
});
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('users/profile', 'UserController#edit')->name('users.edit-profile');
Route::put('users/profile', 'UserController#update')->name('users.update-profile');
Route::get('users','UserController#index')->name('users.index');
Route::post('users/{user}/make-admin', 'UserController#makeAdmin')->name('users.make-admin');
});
Here's the code from PostsController.php
<?php
namespace App\Http\Controllers\Blog;
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Http\Request;
use App\Tag;
use App\Category;
class PostsController extends Controller
{
public function show(Post $post) {
return view('blog.show')->with('post', $post);
}
public function category(Category $category) {
return view('blog.category')
->with('category', $category)
->with('posts', $category->posts()->simplePaginate())
->with('categories', Category::all())
->with('tags', Tag::all());
}
public function tag(Tag $tag) {
return view('blog.tag')
->with('tag', $tag)
->with('posts', $tag->posts()->simplePaginate(3));
}
}
Here's the code from App\Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function post() {
return $this->hasMany(Post::class);
}
}
Here's the code from category.blade.php
#extends('layouts.blog')
#section('title')
Category {{ $category->name }}
#endsection
#section('header')
<header class="header text-center text-white" style="background-image: linear-gradient(-225deg, #5D9FFF 0%, #B8DCFF 48%, #6BBBFF 100%);">
<div class="container">
<div class="row">
<div class="col-md-8 mx-auto">
<h1>{{ $category->name }}</h1>
<p class="lead-2 opacity-90 mt-6">Read and get updated on how we progress</p>
</div>
</div>
</div>
</header><!-- /.header -->
#endsection
#section('content')
<main class="main-content">
<div class="section bg-gray">
<div class="container">
<div class="row">
<div class="col-md-8 col-xl-9">
<div class="row gap-y">
#forelse($posts as $post)
<div class="col-md-6">
<div class="card border hover-shadow-6 mb-6 d-block">
<img class="card-img-top" src="{{ asset($post->image) }}" alt="Card image cap">
<div class="p-6 text-center">
<p>
<a class="small-5 text-lighter text-uppercase ls-2 fw-400" href="#"></a>
{{ $post->category->name }}
</p>
<h5 class="mb-0">
<a class="text-dark" href="{{ route('blog.show',$post->id) }}">
{{ $post->title }}
</a>
</h5>
</div>
</div>
</div>
#empty
<p class="text-center">
No Results found for query <strong>{{ request()->query('search') }} </strong>
</p>
#endforelse
</div>
{{-- <nav class="flexbox mt-30">
<a class="btn btn-white disabled"><i class="ti-arrow-left fs-9 mr-4"></i> Newer</a>
<a class="btn btn-white" href="#">Older <i class="ti-arrow-right fs-9 ml-4"></i></a>
</nav> --}}
{{ $posts->appends(['search' => request()->query('search') ])->links() }}
</div>
#include('partials.sidebar')
</div>
</div>
</div>
</main>
#endsection
If you guys didn't see which file that i don't show up, just ask,.
If you guys see any problems that confusing, i can use teamviewer.
Any Help will be appreciated.
Thank you.
The error told that you don't have posts. Indeed it is. What you have is post() method on Category class, as evidently seen in this line:
public function post() {
You should change this ->with('posts', $category->posts()->simplePaginate()) to be:
public function category(Category $category) {
return view('blog.category')
->with('category', $category)
->with('posts', $category->post()->simplePaginate())
->with('categories', Category::all())
->with('tags', Tag::all());
}
In your model, you defined a post relationship whereas you use a posts relationship then, they're not the same one. You should replace post by posts because it's a to-many relationship.
Your relationship is post and you have multiple ->with('posts', $category->posts()->simplePaginate()). Can you change those to ->with('post') and try again?
public function press (Request $request)
{
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
}
return view('pages.press.index', compact('articles'));
}
I'm receiving an error Undefined variable: articles. Above is the code I'm using in my controller. What is the error that I'm making?
VIew
#if(!empty($articles))
#foreach ($articles as $article)
<div class="col-md-4">
<div class="box border">
<div class="box-header">
<img src="{{ url('http://assets.hobohweb.com/uploads/press/'.$article->image) }}" class="img-fluid" alt="">
</div>
<div class="box-body">
<h6 class="h-2x">{{ $article->title }}</h6>
{{ Carbon\Carbon::parse($article->created_at)->diffForHumans() }} on {{ $article->source }}
</div>
</div>
</div>
#endforeach
#endif
Just check if there are any articles in your search, like:
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
} else {
$articles = [];
}
And use it in the view:
#forelse($articles as $article)
...
#empty
<p>There are no articles!</p>
#endforelse
You are declaring the variable inside the if, but if the condition is false, the variable is never set. Try to use an else condition:
public function press (Request $request)
{
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
} else {
$articles = null;
}
return view('pages.press.index', compact('articles'));
}
You will also need to check if $articles is null in your view.
that's because the variable is never assigned a value and does not exist in the external context of the -if
try to use this
public function press (Request $request)
{
$articles = array();
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
}
return view('pages.press.index', [
'articles' => $articles
]);
}
View
#foreach ($articles as $article)
<div class="col-md-4">
<div class="box border">
<div class="box-header">
<img src="{{ url('http://assets.hobohweb.com/uploads/press/'.$article->image) }}" class="img-fluid" alt="">
</div>
<div class="box-body">
<h6 class="h-2x">{{ $article->title }}</h6>
{{ Carbon\Carbon::parse($article->created_at)->diffForHumans() }} on {{ $article->source }}
</div>
</div>
</div>
#endforeach
I hope this help you
I have created a Post and Comment application. I am trying to link the comments to the id of the post. I am trying to use PHP in a Blade template to do this. I get the error that the variable post_id does not exist. I want to use the #if and #foreach of Blade. The problem seems to be in the #if statement.
Here is my HTML:
<div class="col-md-9">
<div class="row">
#foreach($posts as $post)
<div class="col-md-12 post" id="post{{ $post->id }}">
<div class="row">
<div class="col-md-12">
<h4>
{{ $post->title }}
</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 post-header-line">
<span class="glyphicon glyphicon-user"></span> by {{ $post->user->firstName }} {{ $post->user->lastName }} | <span class="glyphicon glyphicon-calendar">
</span> {{ $post->created_at }} | <span class="glyphicon glyphicon-comment"></span><a href="#">
3 Comments</a>
</div>
</div>
<div class="row post-content">
<div class="col-md-2">
<a href="#">
<img src="/images/random/postimg.jpg" alt="" class="img-responsive postImg">
</a>
</div>
<div class="col-md-10">
<p>
{{ $post->post }}
</p>
</div>
</div>
<div class="row add-comment">
<div class="form-group">
<input type="text" name="addComment" placeholder="Add your comment" class="form-control" v-model="comment">
</div>
<input id="addComment" type="submit" name="submitComment" value="Submit Comment" class="btn btn-default" v-on:click="submitComment" data-id="{{ $post->id }}">
</div>
#if($post->comment->post_id == $post->id)
#foreach($post->comment as $comment)
<div class="row">
<div class="col-md-12 mb-r">
<div class="card example-1 scrollbar-ripe-malinka">
<div class="card-body">
<h4 id="section1"><strong>By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}</strong></h4>
<p>{{ $comment->comment }}</p>
</div>
</div>
</div>
</div>
#endforeach
#endif
</div>
#endforeach
</div>
</div>
Here is my PostController:
public function index(){
$posts = Post::with('comment', 'user')->orderBy('id', 'desc')->limit(20)->get();
return view('post.posts')->with('posts', $posts);
}
You don't need #if statement, remove it. $post->comment is a collection, that 's why your are not getting post_id. if you want to check, then check inside foreach.
#foreach($post->comment as $comment)
<div class="row">
<div class="col-md-12 mb-r">
<div class="card example-1 scrollbar-ripe-malinka">
<div class="card-body">
<h4 id="section1"><strong>By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}</strong></h4>
<p>{{ $comment->comment }}</p>
</div>
</div>
</div>
</div>
#endforeach
You need to add post_id to the comments table and use the relationship:
public function comments()
{
return $this->hasMany(Comment::class);
}
Then you'll be able to load related comments:
Post::with('comments', ....
And iterate over posts and their comments:
#foreach ($posts as $post)
#foreach ($post->comments as $comment)
{{ $comment->content }}
#endforeach
#endforeach
I think if you create relationship between Post model and Comment model (post table and comments table), your #if is useless. I recommend you to check your corresponding models.
Your code should be like this,
Post.php
public function comments(){
return $this->morphMany('App\Comments','commentable');
}
Comment.php
public function commentable(){
return $this->morphTo();
}
in my app Comment model is shared by some other models also.
Eg :- User’s Questions also have comments.
Find more details in laravel:Eloquent page