Im trying to echo the categoryid field from the with('categorys').
My appserviceprovider:
view()->composer('welcome' , function($view){
$view->with('homerings', Ring::where('homepage', '=', 1)->with('categorys')->get()->all());
});
Where i'm trying to echo it in welcome.blade.php.
#foreach($homerings as $ring)
{{ dd($ring->categorys) }}
<div class="col-md-3 col-sm-6 col-xs-6">
<a href="">
<img class="img-responsive homepage-ring" src="{{url($ring->image)}}" alt="{{$ring->title}}">
</a>
</div>
<?php
$i++;
?>
#if($i == 4)
</div>
<div class="row">
#endif
#endforeach
Normal i think it should work like:
{{ dd($ring->categorys->categoryid) }}
But this is not working.
the error:
Undefined property: Illuminate\Database\Eloquent\Collection::$categoryid (View: /resources/views/welcome.blade.php)
As your error tells you "Undefined property ...Collection::$categoryid". It means you are trying to access the categoryid property of a Collection object instead of a Category object.
When you defined a relationship where many can be returned (like hasMany()), Eloquent will return a Collection (more than one) of results. When you define an one-to-one relation, eloquent will return only one result and therefore the Model it is related to.
To retrieve the first model in you collection you could do something like:
$category = $ring->categorys()->first(); // Get first
echo $category->categoryid;
However since your relation will return many I think you would like to have something like:
$categories = $ring->categorys; // Get all categories
#foreach ($categories as $category) // Loop
{{ $category->categoryid }} // Echo categoryid
#endforeach
Hope this helps :)
Ps: the plural form of category is categories
Related
I have an old database filled with info and now i want to display Category names from that DB and getting this error.
Here is my controller
public function forums(){
$cats = Forum_cats::all();
return view ('lapas.forums.index')->with('cats', $cats);
}
}
here is my view
#if(count($cats >1))
#foreach($cats as $cati)
<div class = "well">
<h3>{{$cati->description}}</hr>
</div>
#endforeach
#else
#endif
and here is screen of DB structure
http://prntscr.com/mg5nk1
Ask for more info if needed!
It looks like your operator is misplaced:
#if(count($cats) > 1)
#foreach($cats as $cati)
<div class = "well">
<h3>{{$cati->description}}</hr>
</div>
#endforeach
#else
#endif
It looks like you're trying to loop through these $cats in a Blade template. You might also try forelse:
#forelse($cats as $cati)
<div class = "well">
<h3>{{$cati->description}}</hr>
</div>
#empty
{{-- Action if there are none --}}
#endforelse
Edit: Docs here: https://laravel.com/docs/5.4/blade#loops
Your if is wrong. Try :
#if($cats->count() > 1)
I'm making an attemp to write advanced Eloquent search query filters but when I return the collection to view, I get the following error
Call to undefined method Illuminate\Database\Query\Builder::links()
My Eloquent query builder:
$catalogos = Catalogo::query();
$catalogos->where('catalogo.subcategoria',$filtro)
->join('productos', 'productos.catalogo_id','=','catalogo.id')
->join('productos_precios','productos_precios.segment','=','productos.codigo_oracle')
->join('fotos_productos','fotos_productos.producto_id','=','productos.id')
->select('catalogo.descripcion', 'catalogo.descripcion_corta','catalogo.id','fotos_productos.nombre as ruta', 'productos_precios.precio')
->whereNotNull('fotos_productos.nombre')
->orderBy('precio', 'asc')
->groupBy('catalogo.id')
->paginate(24);
And yes, if I dd($catalogos), it returns me a Builder instance, but why?
My view code is as follows (just in case you're thinking I'm overwriting the value of the $catalogos variable):
#foreach($catalogos as $catalogo)
<div class="producto_tienda">
<a href="{{route('detalle-producto', [$catalogo->id,$catalogo->slug] ) }}">
<div class="foto_producto" style="background-image:url('{{ asset("public/images/tienda/".$catalogo->ruta) }}')">
#if($catalogo->stock>0 && $catalogo->stock<10)
<div class="etiquetas">
<p class="existencia">Últimos productos</p>
</div>
#endif
#if($catalogo->stock==0)
<div class="etiquetas">
<p class="descuento">Agotado</p>
</div>
#endif
</div>
</a>
<a href="{{route('detalle-producto', [$catalogo->id,$catalogo->slug])}}">
<div class="descripcion_producto">{{ $catalogo->descripcion_corta }}</div>
</a>
<div class="precio_producto">{{ money_format( '%.2n' ,$catalogo->precio) }}</div>
</div>
#endforeach
<div class="text-center">
{{ $catalogos->links() }}
</div>
You are not assigning the return value of paginate to anything. It should be:
$catalogos = Catalogo::query()->where('catalogo.subcategoria',$filtro)
->join('productos', 'productos.catalogo_id','=','catalogo.id')
->join('productos_precios','productos_precios.segment','=','productos.codigo_oracle')
->join('fotos_productos','fotos_productos.producto_id','=','productos.id')
->select('catalogo.descripcion', 'catalogo.descripcion_corta','catalogo.id','fotos_productos.nombre as ruta', 'productos_precios.precio')
->whereNotNull('fotos_productos.nombre')
->orderBy('precio', 'asc')
->groupBy('catalogo.id')
->paginate(24);
Now it appears to be working with this:
$catalogos = Catalogo::query();
$catalogos = $catalogos->where('catalogo.subcategoria',$filtro)
->join('productos', 'productos.catalogo_id','=','catalogo.id')
->join('productos_precios','productos_precios.segment','=','productos.codigo_oracle')
->join('fotos_productos','fotos_productos.producto_id','=','productos.id')
->select('catalogo.descripcion', 'catalogo.descripcion_corta','catalogo.id','fotos_productos.nombre as ruta', 'productos_precios.precio')
->whereNotNull('fotos_productos.nombre')
->orderBy('precio', 'asc')
->groupBy('catalogo.id')
->paginate(24);
From the docs:
Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually.
You should follow the documentation and create a manual paginator for your query.
https://laravel.com/docs/5.4/pagination#manually-creating-a-paginator
I wanted to check if variable is there or not in blade ..for that i have used following lines:
#if(is_null($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
The problem is when there is $products on blade I could show inside of foreach loop but when i get empty variable.I couldn't show the message No Data Found instead it shows only empty space?
is there any problem of checking variable inside of blade?
Controller code :
public function productSearch(Request $request)
{
$name = $request->name;
$products = Product::where('name' , 'like', '%'.$name.'%')->get();
return view('cart.product',compact('products'));
}
I generally use PHP count() :
#if(count($products) < 1)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
You may also check with PHP empty() like :
#if(!empty($products))
As you can see in the documentation :
#forelse ($users as $user)
<li>{{ $user->name }}</li>
#empty
<p>No users</p>
#endforelse
This code will allow you to parse all the users and display a list of them. if the $users variables is empty, then it will display a paragraph
so for you :
#forelse ($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse
As of Laravel 5.7, You can also do this:
#empty(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endempty
You can check like
#if(isset($products) && !empty($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
What about checking length?
#if(count($products)) >= 1)
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
Because empty set (i mean a data stucture with zero elements) is not null at all.
php > $a = [];
php > echo is_null($a) ? 1 : 0;
// => 0
is_null Finds whether the given variable is NULL or not. but in our case we need to check whether the value in empty or not for this you can use either isset() or empty() function both work same in your case
while isset — Determine if a variable is set and is not NULL and
empty — Determine whether a variable is empty and also tell variable is set
#if(isset($products) && !empty($products))
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
Do this,
Check is there any records "->count() > 0" then do foreach,
else alert.
#if ($products->count() > 0 )
#foreach($products as $product)
//enter code here
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
For me I will use logic like this
if(!$products->isEmpty()){
return view('cart.product', compact('products'));
}else{
return view('pageerror', compact('products'));
}
then you can call pageerror from your view folder to display any page that does not has data
#forelse($products as $product)
<p>do some thing</p>
#empty
<p>No Products</p>
#endforelse
Refer
Try this
#forelse($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse
I found the most effective (and by far the easiest way) of accomplishing what you're trying here to be as follows.
Assumption #1: You Know The Variable Exists Within The View.
REMEMBER: an empty array will always return false.
Therefore, there is no real need to run it through a function like empty or is null.
Comparing it to null will tell you if it exists or not.
(You could by-pass this assumption by checking to see if the variable is not equal to NULL (it's kind of bloaty if you've passed that variable through to the view, so in my opinion, I would KEEP IT SIMPLE STUPID [KISS] - if you want, you can go all fancy later when it comes to further refactoring).
ANYWAY..
I would stick to pretty similar code as you have now, maybe something like this here would be the code for your view:
#if(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
// {{ $product . “code goes here.” }}
#endforeach
#endif
and the code for your controller would look something like this (you almost had it, remember: "perfect practice makes perfect!" - but yeah, the controller code:
public function productSearch(Request $request)
{
// Easily obtain the name submitted by the form (I assume via the request object
// dependency injection magic
$name = $request->name;
// I would consider using the DB builder tool, as follows, as there is more docs on it
// see: https://laravel.com/docs/5.6/queries - this will return a collection (iterable)
$products = DB::table(‘products’)
->where('name' , 'like', '%'.$name.’%’)
->get();
// simply passing to the view
return view('cart.product', compact('products'));
}
You would also need to include the Product model, DB (Laravel) and (as per usual) the request object, as follows:
// Laravel Dependencies
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
// User Created Model
use App\Product;
Hopefully, this has been helpful!
I am doing project in laravel. In my project there are two tables categories and subcategories. subcategories table has categoryid as foreign key.
subcategoryModel.php has following function
public function category(){
return $this->belongsTo('App\Category');
}
In my blade file I am displaying my subcategories using category object as follows,
blade.php
<div class="col-sm-6 col-align-left">
#foreach($category as $c)
<div class="form-group clearfix">
#if($c->subcategories->count() > 0)
<h4><b>Subcategories: </b></h4>
<div class="form-group clearfix">
#foreach($c->subcategories as $subcategory)
<h4>{{$subcategory->subcategoryname}}</h4>
#endforeach
</div>
#endif
<h4>Add Subcategories</h4>
</div>
#endforeach
</div>
This display correct data,but now I want to display data in the order they are updated/created. Is there any way to display data as per the requirement?
I want to something into the blade file itself. How to do this? Please give suggestions.
You shouldn't do something like that in a blade. Blade should be kept as dumb as possible. Main things should be done in the controller and then passed to the blade. you can do this in your controller:
$categories = Category::with(array('subcategories' => function($query) {
$query->orderBy('created_at', 'DESC');
}))->get();
now the subcategories in the category object will be ordered.
#foreach($c->subcategories()->orderBy('updated_at','asc')->get() as $subcategory)
<h4>{{$subcategory->subcategoryname}}</h4>
#endforeach
Edit: I do like the other answer however OP asked for within the blade file itself
What i'm trying to do is basically have the "latest" episodes show for a series that is has a status of "ongoing" below is the code i have so far.
The problem i a facing is that I can't seem to make the foreach loop for episodes work for the series. Wit hthe current code what it does is shows the same variables. Rather what i think is happening is that it loops the same query for each series so that the same variable pops up for each series.
Can anyone help me out here?
Also the way the episodes are linked is by using the title_id for the titles so in the table for episodes, they are liked by 'title_id', I wouldn't know what to do with that in this sequence though.
<?php $titles = DB::table('titles')->whereNotNull('poster')->where('status', '=', 'ongoing')->orderBy('updated_at', 'desc')->limit(12)->get(); ?>
#foreach ($titles as $title)
<?php $episodes = DB::table('episodes')->orderBy('created_at', 'desc')->limit(1)->get(); ?>
#foreach ($episodes as $episode)
<figure class="col-lg-2 col-md-3 col-sm-4 pretty-figure">
<div class="home-episode-number">
{{ $episode->episode_number }}
</div>
<div class="flip-containerw">
<div class="flipper">
<img src="{{ $episode->poster ? $episode->poster : '/assets/images/noimageepisode.png' }}" alt="" class="img-responsive">
</div>
</div>
<div class="home-anime-name">
{{ str_limit($title->title, 23, '...') }}
</div>
</figure>
#endforeach
#endforeach
You are not following some basic design patterns, like, for instance, the Model-View-Controller structure.
MVC
It's not good practice to have DB calls inside your view, wich you are doing. You should do it inside your model, or in a repository. And pass it trought the controller.
You would avoid a lot of headache if you start using eloquent properly.
Eloquent
Now, answering your question:
If you want to get the episode for the title in the loop, try using a where:
$episodes = DB::table('episodes')->where('title_id,'=',$title->id)->orderBy('created_at', 'desc')->limit(1)->get();
That query will retrieve just one episode (limit(1)).