Get brand name, instead of ID - Laravel 5.8 - laravel

Good someone can help me, I am not doing it well. I have a table called products, in it a field called brand_id, then I have a table called brands, in which I list it by its ID field, this table also contains a column called nombre.
Model producto
class Producto extends Model
{
protected $table = 'productos';
public function marcas()
{
return $this->belongsTo(Marca::class , 'id');
}
}
Model Marca
class Marca extends Model
{
protected $table = 'marcas';
public function producto()
{
return $this->hasMany(Producto::class , 'id_brand');
}
}
Controller
public $categorias, $productos, $ofertados;
public function __construct()
{
$this->productos = Producto::with('marcas')
->latest('id')
->limit(6)
->whereEstado(1)
->get();
}
View
#foreach ($productos as $pro)
<div class="col-4 catProduct">
<div class="col-12 bordeCajon">
#if ($pro->novedad == 1)
<div class="nEntrada">NOVEDAD</div>
#endif
#if ($pro->pvpAntes == null)
#else
<div class="oferta">OFERTA!</div>
#endif
<div class="minHei">
<img src="{{ asset("{$pro->imagen}") }}" alt="">
</div>
<div class="paddingProducto">
#php
/** echo "<pre>"; print_r($pro->marcas);*/
#endphp
<h2> {{ $pro->marcas->mombre }} </h2>
<h3>{{ $pro->producto }}</h3>
<div class="dividerProd"></div>
<h4>{{ $pro->pvpAhora }} <span>€</span></h4>
#if ($pro->pvpAntes == null)
#else
<div class="pvpAntes">{{ $pro->pvpAntes }} <span>€</span></div>
#endif
VER PRODUCTO
</div>
</div>
</div>
#endforeach
Error
Trying to get property 'nombre' of non-object (View: /Applications/MAMP/htdocs/camasLiteras/resources/views/index.blade.php
For example, in the marks table I have 4 marks. In the beginning I have 6 products each with a brand. Well it does what we have done is take the product and put the name of the brand in the same order of the brand table, that is, it does not put the name that it touches. And since there are 6 products but only 4 brands, that's why it says the 'name' of no-object '. If I deactivate two products it doesn't give me an error but it shows in each product a different brand, putting the 4 there are.

Related

Laravel - Property [filieres] does not exist on this collection instance

I have a little one with my school app. I want to display all the faculties of a school. Indeed in my DB a school can have one or more faculties and a faculty can belong to one or more schools.
Model School:
public function filieres ()
{
return $this->belongsToMany('App\Models\Filiere','etablissement_filieres','id_etablissements','id_filieres');
}
public function etablissement_filieres(){
return $this->hasMany('App\Models\Etablissement_filiere');
}
protected $fillable = [
'nom', 'image', 'ville', 'adresse', 'contact_1', 'contact_2',
'email', 'logo', 'presentation', 'brochure', 'localisation',
];
Model table pivot Etablissement_filiere:
public function filiere(){
return $this->belongsTo('App\Models\Filiere');
}
protected $fillable = [
'id', 'id_etablissements', 'id_filieres', 'prise_en_charge', 'prix',
];
Model Filiere:
public function etablissements ()
{
return $this->belongsToMany(Etablissement::class,'etablissement_filiere');
}
protected $fillable = [
'nom', 'diplome_requis', 'diplome_obtenu', 'prix', 'duree', 'type',
];
Controller:
public function show($id)
{
$faculty = Etablissement_filiere::where('id_etablissements','=','$id')->get();
return view('etablissements/edhec/touteslesfilieresedhec', compact('faculty','etablissements'));
}
Blade view:
#foreach($faculty->filieres as $filiere)
<div class="container bg-fil py-4 my-5">
<div class="row pl-5">
<div class="col-md-9">
<h6 class="font-weight-bold">{{ $filiere ->nom}} <br>
<span class="text-primary"> {{ $filiere ->diplome_obtenu}}</span></h6>
</div>
<div class="col-md-3 pt-n5">
<img src="{{asset($etablissement->image)}}" alt="">
</div>
</div>
<div class="row pl-5 mt-md-n5">
<div class="col-md-6">
<h6> <strong> Diplôme réquis</strong>: {{ $filiere ->diplome_requis}} <br>
<strong>Durée</strong>: {{ $filiere ->duree}} <br>
<strong>Montant de la formation</strong>: {{ $etablissement_filieres ->prix}}</h6>
</div>
<div class="col-md-6">
<h6> <strong> Mode d'etude</strong>: {{ $filiere ->type}} <br>
<strong>Prise en charge</strong>: {{ $etablissement_filieres ->prise_en_charge}}</h6>
</div>
</div>
<div class="row pl-5 mt-4">
<div class="col-md-6">
INSCRIVEZ VOUS MAINTENANT
</div>
</div>
</div>
#endforeach
I am trying to display all the faculties in the school but I have this error:
Property [filieres] does not exist on this collection instance.
Can you tell me where the error is preventing?
Your immediate view error is when it tries to evaluate $faculty->filieres.
Calls to something like Model::where()->get() return a Collection instance (which is like an iterable group) of Models, not a single Model. Even if that collection only contains one model, it's still a group and not the model itself.
So, $faculty = Etablissement_filiere::where('id_etablissements','=','$id')->get(); returns a Collection, not a single model. A single model may have a filieres property, but the Collection instance (which itself is a class in Laravel) does not. So, if what you want is the first result only, and not a collection, end that line with ->first() instead of ->get().
However even if you fix that, you also have a second problem. You're getting an instance of the pivot model Etablissement_filiere, and then trying to access the filieres property on it (which it doesn't have). Instead, you should be getting an instance of the School model. If you've defined your relations correctly, Laravel will take care of finding the pivot for you, so you normally wouldn't access a pivot model directly unless you had a particular reason to. So, instead try this in your controller:
public function show($id)
{
$establissement = Etablissement::find($id);
$faculty = $establissement->filieres;
return view('etablissements/edhec/touteslesfilieresedhec', compact('faculty','etablissement'));
}
and then in your view:
#foreach($faculty as $filiere)
There are cleaner ways to do this (e.g. look into some tutorials on route-model binding), but that should at least solve the error for your current code.
Change your code to
public function show($id)
{
$faculty = Etablissement_filiere::where('id_etablissements','=',$id)->first();
return view('etablissements/edhec/touteslesfilieresedhec', compact('faculty','etablissements'));
}

How to show data in blade by id

I have to make a website for student hostels in my country I have a special page for every hostel that shows its all photos and property but I don't know how can I do this with the hostel id when I have a hostel table if someone can help me, please!
thank's for all
This is my hostel controller code:
class HostelDetailsController extends Controller
{
public function index(Request $request,$detail_id)
{
// $id = $request->query($detail_id);
$file_details = HostelDetails::all();
$files = Attachment::get();
return view('khabgah_details', compact(['file_details', 'files']));
}
}
This is my hostel page blade code:
#foreach($file_details as $file)
<div class="card-title text-center">
<div class="mt-4"></div>
<i class="fa fa-home mt-4 text-center" style="font-size:45px;"></i>
<h5 class="mt-3 text-center"> لیلیه نرگس </h5>
<h6 class="fa fa-phone"> شماره تماس: {{ $file->phone_number }} </h6>
</div>
#endforeach
It doesn't show any error message but when I load the page it shows all my records in the table
//You can get the id from the index page of the hostel
public function show($id)
{
$details = Detail::where('hostel_id', '=', $id)->get();
return view('HostelDetailPage',compact('details'));
}

how to get single category and its subcategories in laravel blade

I have a code, where I am getting all the categories and its subcategories from the table, but i want to get a single category and it's subcategories from the categories table display in the laravel blade navigation file.
For example, I have shoes and shirts categories and their subcategories in the table, I want to display only shirts category and its subcategories show in the front end. please help me to achieve this.
I am getting all the categories and its subcategories from the table
Route:
//here i have added route url for link and well to display categories
Route::get('/products/{url}', 'ProductController#products');
Controller Method:
//this is function/method
public function products($url = null)
{
$countCategory = Category::where(['url'=>$url, 'status'=>1])->count();
if($countCategory==0){
abort(404);
}
//Get All Categories and Sub Categories
$categories = Category::with('categories')->where(['parent_id' => 0])->get();
$categoryDetails = Category::where(['url' => $url])->first();
if ($categoryDetails->parent_id==0) {
//if url is main category url
$sub_categories = Category::where(['parent_id'=>$categoryDetails->id])->get();
foreach ($sub_categories as $sub_cat) {
$cat_ids[] = $sub_cat->id;
}
// echo $cat_ids; die;
$productsAll = Product::whereIn('category_id',$cat_ids)->where('status', 1)->get();
} else {
$productsAll = Product::where(['category_id' => $categoryDetails->id])->where('status', 1)->get();
}
return view('products.listing')->with(compact('categories', 'categoryDetails', 'productsAll'));
}
Category Model:
public function categories()
{
return $this->hasMany('App\Category', 'parent_id');
}
Balde (View) file:
<div class="side-bar col-md-12">
<h3 class="agileits-sear-head">Category</h3>
<div class="panel-group" id="accordian">
{{-- this is the basic way to show the categores inthe table --}}
<?php //echo $categories_menu ?>
#foreach ($categories as $cat)
#if($cat->status=="1")
<div class="panel-heading" >
<h4 class="panel-title">
<a href="#{{ $cat->id }}" data-toggle="collapse" data-parent="#accordian">
<span class="badge pull-right"><i class="fa fa-plus"></i></span>
{{ $cat->name }}
</a>
</h4>
</div>
<div id="{{ $cat->id }}" class="panel-collapse collapse">
<div class="panel-body" >
<ul style="list-style: none; margin-left:30px;">
#foreach ($cat->categories as $sub_cat)
#if($sub_cat->status=="1")
<li>{{ $sub_cat->name }}</li>
#endif
#endforeach
</ul>
</div>
</div>
#endif
#endforeach
</div>
</div>
I appreciate the solution as earlier as possible
sir, I have a question that, I do not want to display my all categories in the sidebar, instead of I want only one category like shoe category and its subcategory I want to display, please guide me how to achieve this. and also i want different category sidebar for different categories,
example,
let's assume we have a shirts listing page where all the shirts, T-shirts and many more shirts related to Shirts Category only.
and i want only Shirts and its subcategory to display in the sidebar.
if i have shoes category and i want to display only shoes category and its subcategory in the sidebar.
please guide me how to achieve this sir,
It is very simple hasMany-belongsTo relationship, let me show you.
<?php
namespace App\models;
use App\pivotes\Catagory;
use Illuminate\Database\Eloquent\Model;
class Catagory extends Model
{
public function children()
{
return $this->hasMany(SELF::class, 'parent_id');
}
public function parentCategory()
{
return $this->hasMany(SELF::class, 'id', 'parent_id');
}
}
Migration file will be
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category');
$table->unsignedInteger('parent_id')->nullable();
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('comments');
});
for /categories/{category}
Controller method will be
CategoryController extends Controller {
public function show(Category $category)
{
return view('categories.show', $category);
}
}
In view
#foreach( $category->children as $subCategory )
{{ $subcategory->category }}
#endforeach

Laravel Select the First Row From HasMany Relation

I have 2 table where 1 products have many prodphotos
I can retrieve all prodphotos from products with the same id, but my case is listing all the products but only take 1 photo from prodphotos.
Controller :
public function daftarproduk()
{
$produks = Product::orderBy('created_at', 'desc')->get();
$select = Product::with('prodphotos')->firstorfail();
$photo = $select->prodphotos->pluck('photo');
$kategori = Category::orderBy('created_at', 'asc')->get();
return view('guest.daftarproduk')
->with('produks',$produks)
->with('kategori',$kategori)
->with('select',$select)
->with('photo',$photo);
}
View :
#foreach($produks as $value)
<div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
<div class="box-product">
<div class="img-wrapper">
<a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
<img alt="Product" src="images/gambarproduk/thumb_{{ i dont know what i must throw here to only get first picture }}">
</a>
</div>
<h6>{{$value->name}}</h6>
</div>
</div>
#endforeach
I dont know what function I must use to get the first photo name from $select or $photo from controller. or my foreach logic is wrong? Please help me.
Add a featured photo relation with hasOne type to your Product model.
Product model
public function featuredPhoto() {
return $this->hasOne(PhotosModel);
}
In your controller
public function daftarproduk()
{
// Get the products with featured image
$produks = Product::with('featuredPhoto')->orderBy('created_at', 'desc')->get();
$kategori = Category::orderBy('created_at', 'asc')->get();
return view('guest.daftarproduk')
->with('produks',$produks)
->with('kategori',$kategori);
}
View
#foreach($produks as $value)
<div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
<div class="box-product">
<div class="img-wrapper">
<a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
<img alt="Product" src="images/gambarproduk/thumb_{{ $value->featuredPhoto->photo }}">
</a>
</div>
<h6>{{$value->name}}</h6>
</div>
</div>
#endforeach

get category name in a post record

I have a list containing article posts from all categories. I want to display the category tag in each post on the list and I tried this :
<article class="post bg z-depth-1">
<?php foreach ($article_list as $article): ?>
<div class="post-img">
<a href="post.html">
<img class="retina" src="{{ asset('image/' . $article->image) }}" width="820" height="500" alt="Post Image">
</a>
</div>
<div class="post-content">
<div class="post-header center-align">
<div class="tags">
{{ $article->category->title }}</div>
<h2 class="post-title">{{ $article->title }}</h2>
<div class="date">Posted on {{ Carbon\Carbon::parse($article->created_at)->format('F j, Y') }}</div>
</div>
<div class="post-entry">
<p>sss</p>
</div>
<div class="post-footer">
<div class="post-footer-item">
<span class="text">Read More</span> <i class="fa fa-arrow-circle-right"></i>
</div>
</div>
</div><!-- .post-content -->
<?php endforeach ?>
</article><!-- .post -->
and it gave me error Undefined property: stdClass::$category and I don't know why, I already define the relationship in each model Article and Category. Thanks for the help!
In Article model :
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
In Category model :
public function article() {
return $this->hasMany('App\Article', 'category_id');
}
Controller :
public function index() {
$article_list = Article::all();
return view('article/index', compact('article_list', $article_list));
}
What you need to do is eager load those relationships in your controller.
When you pull the records do it like this:
$article_list = Article::with('category')->get();
https://laravel.com/docs/5.3/eloquent-relationships#eager-loading
Change this: $article->category->title
To this: $article->category()->title
When you define the relationship in your model you are also creating a function not a property called category.
public function category()
{
return $this->belongsTo('App\Category');
}
In Category model :
public function article() {
return $this->hasMany('App\Article');
}
Controller :
public function index() {
$article_list = Article::all();
return view('article/index', compact('article_list'));
}
This should work for you now like this.

Resources