I have this controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Category;
class CategoriesController extends Controller
{
public function index()
{
$categories = Category::all();
return view('home', ['categories'=> $categories]);
}
}
and my blade is something like this(his call "home.blade.php")
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/js/swiper.min.js"></script>
<div class="container">
<div class="row text-center mb-3">
<div class="col-md-12">
<h2>Categorias</h2>
<hr>
#foreach($categories as $cat)
<button>{{ $cat->CATEGORIA_NOME }}</button>
#endforeach
</div>
</div>
the Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = ['CATEGORIA_NOME', 'CATEGORIA_DESC'];
protected $table = 'CATEGORIA';
protected $primaryKey = 'CATEGORIA_ID';
protected $timestamp = false;
public function categorias()
{
return $this->hasMany(Product::class, 'CATEGORIA_ID');
}
}
but i still receiving the error:
Undefined variable $categories
I tried to using the
$categories = Category::all();
return view('home', ['categories'=> $categories]);
or
return view('home')->with('categories', $categories);
but it did not work
try this :
return view('home', ['categories'=> Category::all()]);
if doesn't work try to dump your category model, see if the data is out or not
Try using compact(), like this.
$categories = Category::all();
return view('home', compact('categories'));
Related
I am trying to implement a search through multiple tables. The project is an online store with 3 distinctive tables, Products, Categories and Brands. I can only search through the Products table but can't seem to get the same search field from my blade file to search either the categories or the brands and return results of the associated products.
My Blade search input
<form action="{{ url('/search-products') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<div class="row" style="display: flex;">
<input class="typeahead form-control form-control-lg" type="text" name="product" id="product" placeholder="Search item to buy here..." style="width: 220px;">  
<button type="submit" class="btn btn-primary">
<i class="ti-search"></i>
</div>
</div>
</form>
My search function in my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Image;
use App\Category;
use App\Brands;
use App\Product;
use DB;
class ProductController extends Controller
{
public function searchProducts(Request $request) {
$product = $request->input('product');
$categories = Category::with('categories')->where(['parent_id' => 0])->get();
$productsAll = Product::query()->where('product_name', 'LIKE', "%{$product}%")
->orWhere('state', 'LIKE', "%{$product}%")
->orWhere('lga', 'LIKE', "%{$product}%")
->orWhere('category_id', 'LIKE', "%{$product}%")->where('status', 1)->get();
$breadcrumb = "<a href='/'>Home</a> / ".$product;
return view('pages.results')->with(compact('categories', 'productsAll', 'product', 'breadcrumb'));
}
}
My Products Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
use Session;
use DB;
class Product extends Model
{
protected $with = ['category'];
public function category()
{
return $this->hasMany('App\Category', 'id');
}
}
My Category Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function products(){
return $this->hasMany('App\Product','id');
}
}
My Brands Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Brands extends Model
{
//
}
To find Categories that have Products like the given searchTerm, you could do the following:
SearchController.php
class SearchController extends Controller
{
public function index(Request $Request)
{
$searchTerm = $request->product;
$categories = Categories::whereHas('products', function ($query) use ($searchTerm){
$query->where('name', 'like', '%'.$searchTerm.'%');
})
->with(['products' => function($query) use ($searchTerm){
$query->where('name', 'like', '%'.$searchTerm.'%');
}])->get();
return view('search-results-view', compact('categories));
}
}
You'll then have a collection of Categories with the Products eager loaded.
Having passed the $categories to the returned view (above), you'll be able to loop over the Categories and the related Products in your blade file.
search-results-view.blade.php
#foreach ($categories as $category)
<h4>{{ $category->name }}</h4>
#foreach ($category->products as $product)
{{ $product->name }}
#endforeach
#endforeach
You can use the same principal to work on your Brands model.
I was able to solve the problem by using the join function of eloquent to query multiple tables. I edited my search function in my controller as follows
public function searchProducts(Request $request) {
$product = $request->input('product');
$categories = Category::with('categories')->where(['parent_id' => 0])->get();
$productsAll = Category::query()->join('products', 'products.category_id', '=', 'categories.id')
->where('categories.name', 'LIKE', "%{$product}%")
->orWhere('products.product_name', 'LIKE', "%{$product}%")
->where('products.status', 1)->get();
$breadcrumb = "<a href='/'>Home</a> / ".$product;
return view('pages.results')->with(compact('categories','productsAll','product','breadcrumb'));
}
And My Category Controller
class Category extends Model implements Searchable
{
protected $table = 'categories';
protected $fillable = [
'name'
];
public function categories(){
return $this->hasMany('App\Category','id');
}
public function products(){
return $this->hasMany('App\Product','id');
}
}
And My Product Controller
class Category extends Model implements Searchable
{
protected $table = 'categories';
protected $fillable = [
'name'
];
public function categories(){
return $this->hasMany('App\Category','id');
}
public function products(){
return $this->hasMany('App\Product','id');
}
}
For my Laravel assignment I am working on a store, and using models to create the pages of shown products. However, the view pages gives me the error of class not found. I am a bit stumped on that to be honest.
Here is the controller I use:
namespace App\Http\Controllers\Shop;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Product;
class ShopController extends Controller{
public function displayProduct($cat, $pro) {
$data['category'] = Product::getProduct($cat, $pro);
return view('shop.prosuct', $data);
}
public function displayCategory($slug) {
$data['category'] = Category::getCategory($slug);
return view('shop.category', $data);
}
public function displayShop() {
$data['categories'] = Category::getCategories();
return view('shop.shop', $data);
}
}
Said Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function category() {
return $this->belongsTo('App/Model/Category');
}
public static function getProduct($cat, $pro){
$product = self::where('slug', $pro)->firstorFail();
$product_cat = $product->category->slug;
//retun ($product_cat === $cat) ? $product_cat: false;
abort_if($product_cat !== $cat, 404);
return $product;
}
//use HasFactory;
}
the Category model (just in case):
<?php
namespace App\Models;
//use App\Http\Modles;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function products() {
return $this->hasMany('App\Model\Product');
}
public static function getCategory($slug){
return self::where('slug', $slug)->firstOrFail(['id', 'slug']);
}
public static function getCategories() {
return self::orderBy('slug')->get();
}
//use HasFactory;
}
and finally, the view page:
#extends('template')
#section('content')
<h1 class="mb-5"> {{$category->name}} </h1>
<div class="row">
#foreach ($category->products as $product)
<div class="col-md-4 mb-5">
<div class="pro-container">
<h3>{{$product->name}}</h3>
<img src="{{asset('images/products/' . $product->image)}}">
<h4> ₪ {{$product->price}} </h4>
<a class="btn btn-primary" herf=""> ADD TO CART </a>
<a class="btn btn-primary" herf="{{url()->current() . '/' . $product->slug}}"> READ MORE </a>
</div>
</div>
#endforeach
</div>
#endsection
The idea is to save the space and create the page of each category to show its products; I have 3 categories in total it needs to be done for.
Thank you in advance for your help! (also, I'm using Laravel 7)
In both of your relationships you are referencing the Model directory instead of the Models one:
# Category.php
public function products() {
return $this->hasMany('App\Model\Product');
} ^^^^^^
# Product.php
public function category() {
return $this->belongsTo('App\Model\Category');
} ^^^^^^^^
Fix them and it should work now.
To avoid this kind of issues, given that you're dealing with strings, why not make use of this other (better) syntax? It's also IDE-friendly and supports refactoring:
# Category.php
public function products() {
return $this->hasMany(Product::class);
} ^^^^^^^^^^^^^^
# Product.php
public function category() {
return $this->belongsTo(Category::class);
} ^^^^^^^^^^^^^^^
I have the following models:
namespace App;
use Illuminate\Database\Eloquent\Model;
class forum_category extends Model
{
//
protected $table = 'forum_category';
public function posts()
{
$this->hasMany('App\forum_post');
}
}
And
namespace App;
use Illuminate\Database\Eloquent\Model;
class forum_post extends Model
{
//
protected $table = 'forum_post';
public function category()
{
$this->belongsTo('App\forum_category');
}
}
in my controller i attempt to get all categories with their posts:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\forum_category as forum_category;
class ForumController extends Controller
{
public function __construct()
{
}
public function index ()
{
$categories = forum_category::all();
return view('forum', ['categories' => $categories]);
}
public function createPost()
{
}
public function createReply()
{
}
}
However it seems to only be returning my categories.
Can someone tell me what ive done wrong?
The query should look like this:
$categories = forum_category::with('posts')->get();
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
If you have category_id in the forum_post table, this will load categories with related posts.
Then just iterate over the collection to get posts:
#foreach ($categories as $category)
#foreach ($category->posts as $post)
{{ $post->title }}
#endforeach
#endforeach
Also, the relationship should be:
public function category()
{
return $this->belongsTo('App\forum_category');
}
I just finishing my blog, using laravel, and I want to add a comment feature on it, but i got few errors like this, can anyone help me, please??,
sorry for my English, English is not my native language,
Thank you :)
(1/1) ErrorException
Undefined offset: 1
Here is my AdminBlog.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AdminBlog extends Model
{
protected $table = 'admin';
protected $fillable = ['title','text','images','slug'];
public function comment(){
return $this->hasMany('App\Comment');
}
}
Comment.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comment';
protected $fillable = ['name','email','text','post_id'];
public function post(){
return $this->belongsTo('App\AdminBlog');
}
}
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AdminBlog;
use App\Comment;
class BlogController extends Controller
{
//Index
public function index(){
$post = AdminBlog::all();
return view('blog/index', compact('post'));
}
//Show
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
}
show.blade.php
<div class="col-md-12 post-comment-show">
#foreach($post->comment() as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
You should use:
<div class="col-md-12 post-comment-show">
#foreach($post->comment as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
Note that, you have used comment(). Also, you should use a plural name for a hasMany relationship, so comment should be comments.
Also, in your show method, you should use something like the following:
public function show($id)
{
$post = AdminBlog::with('comment')->findOrFail($id);
return view('blog/show', ['post' => $post]);
}
Try the following
$post->comment()->get()
or
$post->comment
when calling a relationship with ()it returns a instance of the query builder and allows you to filter the object. If you remove the call it without () it returns you a collection which is array accessible
Another suggestion if you have many comments you should name your relationship plural.
in this case:
public function comments(){
return $this->hasMany('App\Comment');
}
// Use it like this
$post->comments
You need to change your show function:
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
TO
public function show($id){
$post = AdminBlog::with('comment')->where('admin.id',$id)->get();
return view('blog/show', compact('post'));
}
Hope this work for you!
today I am trying to fix the following error. It is telling me for some weird reason that the class for my relationship in laravel does not exist? I am not sure why as the code looks perfectly fine to me.
Class 'App\Database\Website\Roleplay\GovermentRole' not found
Where it is happening:
{{ $governmentMember->government_role->government_title }}
Full code:
#if ($higherGovernment->count() > 0)
#foreach ($higherGovernment as $governmentMember)
<div class="col-md-10">
<div class="col-md-12" style="margin-left:-40px;">
<div class="col-md-1" style="margin-top:-16px;"><img src="http://mywebsite.com/images/get_character_look.php?look={{ $governmentMember->user->look }}&size=b&direction=3&head_direction=3"></div>
<div class="col-md-9" style="margin-left:40px;">
<h4>{{ $governmentMember->government_role->government_title }}<small>The Crown</small></h4>
<p><font color="#aaa">Department here</font></p><br>
</div>
</div>
</div>
#endforeach
#else
There are currently no candigates working in this category.
#endif
Here is my Roleplay Stat class, which $governmentMember is an instance of:
<?php
namespace App\Database\Website\User;
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovermentRole', 'government_id');
}
}
Here is my GovernmentRole class:
<?php
namespace App\Database\Website\Roleplay;
use Eloquent;
class GovernmentRole extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_government_roles';
public $timestamps = false;
protected $fillable = [];
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
}
Here is the controller for the blade page:
<?php
namespace App\Http\Controllers\Frontend\User;
use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;
class GovernmentController
{
public function getView()
{
$royalty = Cache::remember('government.royalty', 1, function() {
return GovernmentRole::where('government_type', 'royalty')->first()->stats;
});
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
$seniorGovernment = Cache::remember('government.senior_government', 1, function() {
return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
});
$juniorGovernment = Cache::remember('government.junior_government', 1, function() {
return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
});
return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
}
}
Sorry to tell you this, but there is a 'typing error' in your relationship method
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovermentRole', 'government_id');
}
You are looking for 'GovermentRole' while the class' name is 'GovernmentRole'. Notice the extra 'n' character after 'r'
The error is because GovermentRole file does not available at specified path i.e.
App\Database\Website\Roleplay\GovermentRole
Make sure the class is in right folder. Then run this command:
composer dumpauto