Access both table data through relation - laravel-5

I have two tables with a Many-to-Many relation. So I created a third table:
professor < -- > turma | Pivot: professor_turma
Here is my model's code:
class Professor extends Model
{
public function turmas()
{
return $this->belongsToMany('App\Turma', 'professor_turma', 'cod_professor', 'cod_turma');
}
}
class Turma extends Model
{
protected $table = 'turma';
public function professores(){
return $this->belongsToMany('App\Professor');
}
}
my Professor's Controller:(The one my route redirects to)
class ProfessorController extends Controller
{
public function getProfessorList()
{
return View::make('professor', [
'professor' => Professor::orderBy('nome','asc')->get()
]);
}
}
In my view, I'm trying to access the data of both tables (Professor, Turma).
<ul class="prof-list col-md-4">
#foreach($professor as $prof)
<li>
<h3 data-id="{{ $prof->cod_professor }}" class="prof-name">{{ $prof->cod_professor }} - {{ $prof->nome }}
<input type="checkbox" name="" value="" class="check_prof" />
</h3>
<ul class="list-disc">
#foreach($prof->turmas as $disc)
<li data-dia="{{ $disc->dia_semana }}" data-time="{{ $disc->hr_inicio}}" data-id="{{ $disc->cod_disciplina }}">{{ $disc->nome_disciplina }} </li>
#endforeach
</ul>
</li>
#endforeach
I'd like to know how could I access Turma's data without the second #foreach without using $disc. Is it possible? How ?
#foreach($prof as $disc)
Why I can't do something like:
#for($i = 0; $i < 1; $i++)
{{ $professor->turmas[$i]->dia_semana }}
#endfor

The problem is that you need to eager load the "turmas" instead of lazy loading.
This will also make your code more effecient since it won't query the DB for each "professor" row.
See: http://laravel.com/docs/5.1/eloquent-relationships#eager-loading
This should fix the problem:
Professor::with('turmas')->orderBy('nome','asc')->get()

Related

Show category posts in Laravel is not working

I want to show posts that are in a category by clicking on them, but when I click on a category,$articles in category.blade.php returns null.
$articles should return articles that have a specific category
this is my index.blade.php:
<div class="tab-pane fade" id="show-categories" role="tabpanel">
<h6 class="sidebar-title">Categories</h6>
<div class="row link-color-default fs-14 lh-24">
#foreach($categories as $category)
<div class="col-6">
<a href="{{ route('cms.category', $category->id) }}">
{{ $category->name }}
</a>
</div>
#endforeach
</div>
</div>
category.blade.php:
#extends('layouts.app')
#section('content')
#forelse ($articles as $article)
<h1>{{$article->title}}</h1>
#empty
<span>array is empty</span>
#endforelse
#endsection
router:
Route::get('cms/categories/{category}', [articlesController::class, 'category'])->name('cms.category');
and articlesController:
public function category(Category $category)
{
return view('cms.category')
->with('category', $category)
->with('articles', $category->articles()->searched()->simplePaginate(3))
->with('categories', Category::all())
->with('tags', Tag::all());
}
Please, don't forget to define the relationship from Category to Article on your model. Like: one category has many articles. For example:
On your Category.php model:
public function articles()
{
return $this->hasMany(Article::class);
}
Then on your, controller, you may call the relationship like this way:
public function category(Category $category)
{
$articles = Category::with("articles")->where("id", $category->id)->simplePaginate(3);
return view('cms.category')
->with('category', $category)
->with('articles', $articles)
->with('categories', Category::all())
->with('tags', Tag::all());
}
Please share the model file and second I prefer to write the category method in a different way.
public function category($category_id)
{
try {
$articles= Article::where('id', $category_id)->get();
return view('cms.category', $articles);
} catch (\Throwable $th) {
Log::error($th->getMessage());
}
}
Let me know if you still face any issue. Try to use dd $articles ..

Get brand name, instead of ID - Laravel 5.8

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.

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

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.

Is there a more efficient way for grabbing the count of a model within the view? Laravel

I have Images. Each image has comments, and each comment has likes. In my view I'm wanting to display the number of likes a comment has by doing something like this:
#foreach ($images as image)
<img href="$image->url">
<div class="comment-box">
#foreach ($image->comments as $comment)
<div class="comment">
<span class="comment-owner">{{ $comment->owner()->name }}</span> {{ $comment->body }}
<div class="likes">
{{ $comment->likes()->count() }} // ** HERE IS MY N+1 PROBLEM **
</div>
</div>
#endforeach
</div>
#endforeach
However now I'm fetching a query each time there is a comment. There could be hundreds of comments on a page, so id be getting hundreds of queries just to find the count() for likes.
I believe there is a way you can grab the count in a controller by doing something like
DB::raw('count(*) as like_count')
but I do not know how to implement this in my situation. Can I put this kind of thing in my model so that I can always call something like {{ $comment->likes()->like_count }}? How can I make $comment->likes->count() work without having the N+1 problem?
Here is some more code:
Media Model
class Media extends Eloquent {
public function comments()
{
return $this->hasMany('Comment');
}
}
Comment Model
class Comment extends Eloquent {
public function media()
{
return $this->belongsTo('Media');
}
public function likes()
{
return $this->hasMany('Like');
}
}
Like Model
class Like extends Eloquent {
public function comment()
{
return $this->belongsTo('Comment');
}
}
My controller
public function imageViewer($id)
{
$images = Media::with(['comments' => function($query) {
$query->with('likes');
}])->where('resource_id', $id)->simplePaginate(1);
return View::make('image-viewer', compact('images'));
}
Why don't you just use blade's count like this count($comment->likes) assuming that $comment->likes gets the list of likes for a comment
#foreach ($images as image)
<img href="$image->url">
<div class="comment-box">
#foreach ($image->comments as $comment)
<div class="comment">
<span class="comment-owner">{{ $comment->owner()->name }}</span> {{ $comment->body }}
<div class="likes">
{{ count($comment->likes) }}
</div>
</div>
#endforeach
</div>
#endforeach
Thanks to #lukasgeiter for pointing out a mistake in the comments

Resources