Laravel Collection get one of values by key - php

I'm new to Laravel and I'm trying to get one of the values in one collection by one ID retrieved from another collection.
My function returns 2 Collections:
public function index()
{
$category = BlogCategory::all(['id', 'name']);
$post = BlogPost::orderBy('id', 'desc')->take(14)->get();
return view('blog.index', ['posts' => $post], ['categories' => $category]);
}
In a foreach loop I'm getting values from collections:
#foreach($posts as $post)
#if($loop->iteration > 2)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $categories->get($post->category_id) }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endif
#endforeach
I'm partially getting the result as you can see in the image below, but I want to get only the name.
Here is the code that I'm trying to figure out
{{ $categories->get($post->category_id) }}
If there is a better or correct way to do it, let me know.
Blog Posts migration:
public function up()
{
Schema::create('blog_posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->longText('content');
$table->mediumText('slug');
$table->bigInteger('author_id')->unsigned();
$table->bigInteger('category_id')->unsigned();
$table->timestamps();
$table->foreign('author_id')->references('id')->on('blog_authors');
$table->foreign('category_id')->references('id')->on('blog_categories');
});
}

You should put in place the relationships between BlogPost and BlogCategory models, seen that you already have a category_id field in BlogPost model, i.e.:
in BlogPost Model:
public function category(){
return $this->belongsTo(\App\BlogCategory::class);
}
in BlogCategory Model:
public function posts(){
return $this->hasMany(\App\BlogPost::class);
}
Next you can eager load categories with the $posts in your controller with only two queries:
public function index()
{
$posts = BlogPost::with('category')->orderBy('id', 'desc')->take(14)->get();
return view('blog.index', compact('posts'));
}
Then in your view you can access each $post->category object directly because eager loaded in the controller:
#foreach($posts as $post)
#if($loop->iteration > 2)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $post->category->name }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endif
#endforeach

It could be optimized, first, you need to make relation one to many from categories to posts
first: make sure that you have in posts migrations category_id column
Second: Open Category Model and write this method this will allow you to fetch posts that belong to the category
public function posts(){
return $this->hasMany(\App\Post::class);
}
Third: open shop model and write this method this will allow you to fetch category that belongs to the post
public function catgeory(){
return $this->belongsTo(\App\Category::class);
}
Finally: you will edit your view like this one
#foreach($posts as $post)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $post->category->title }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endforeach
and of course, you wouldn't call categories in your controller anymore
public function index()
{
$post = BlogPost::orderBy('id', 'desc')->take(14)
->with('category')->get();
return view('blog.index', ['posts' => $post]);
}

Maybe it better use a relation to drive this situation. You can load in the controller the data in this way.
In the Model Post:
function categories(){
return $this->belongsToMany('App\BlogCategory')->select(array('id', 'name');
}
Maybe is hasOne -> the relationship if you don't have a table pivot...
In the Controller:
public function index()
{
$data['posts'] = BlogPost::orderBy('id', 'desc')->take(14)->with('categories')->get();
return view('blog.index', $data);
}
In the View:
#foreach($posts as $post)
#if($loop->iteration > 2)
<div class="col-sm-6 col-md-3 d-flex justify-content-center other-post">
<a href="#">
<img src="#" alt="">
<p class="post-category">{{ $post->categories->name }}</p>
<h5 class="post-title">{{ $post->title }}</h5>
</a>
</div>
#endif
#endforeach

this line $categories->get($post->category_id) return for you an array of category, so the solution for you here is just like bellow:
{{ $categories->get($post->category_id)['name'] }}

Related

Laravel 8 eloquent querying with relations

I want to display all the products that have at least one image, then I display one of the image as the card's cover. But the query I made is displaying cards as many as images in the database.
Models
class Product extends Model {
public function getAllData()
{
$data = DB::table('product')
->select('product.*', 'product_images.img')
->join('product_images', 'product_images.product_id', '=', 'product.id')
->paginate(9);
return $data;
}
}
class ProductImage extends Model
{
public function product()
{
return $this->belongsTo(product::class);
}
}
Controller
public function index()
{
$img = ProductImage::find(1);
$data = [
'card' => $img->product->getAllData(),
];
return view('view', $data);
}
View
#foreach ($card as $item)
<div class="card shadow m-3" style="width: 18rem; heigth:24rem">
<div class="inner">
<img class="card-img-top" src="{{$item->img}}" alt="Card image cap">
</div>
<div class="card-body text-center">
<h5 class="card-title">{{$item->name}}</h5>
<p class="card-text">{{$item->description}}</p>
Check them out...
</div>
</div>
#endforeach
So I want to retrieve all Product instances with ProductImage instances in single array $card. What is the right way to do this?
Thanks in advance.
What I understand from you're requirement is you want to display all the products which have atleast 1 image against a product.
public function index()
{
$products = Product::has('image')
->with('image')
->get();
$data = [
'card' => $products,
];
return view('view', $data);
}
This will return all the products which has 1 image and the image can be used via image relation
#foreach ($card as $item)
<div class="card shadow m-3" style="width: 18rem; heigth:24rem">
<div class="inner">
<img class="card-img-top" src="{{$item->image->img}}" alt="Card image cap">
</div>
<div class="card-body text-center">
<h5 class="card-title">{{$item->name}}</h5>
<p class="card-text">{{$item->description}}</p>
Check them out...
</div>
</div>
#endforeach
Product Model
class Product extends Model
{
public function image()
{
return $this->hasOne(ProductImage:class);
}
public function images()
{
return $this->hasMany(ProductImage:class);
}
}
I have only used Laravel Eloquent, so the way I've shown the rendering of the products in view might be wrong

show the categories and project in view

my questions may be a bit of a beginner, but please be patient, thank you
I want to display the projects related to each category in the following code in the second foreach, but now all the projects are displayed
view
#foreach($categories as $category)
<div id="section-{{ $category->id }}" class="section">
<h3 class="fnt_gh fnt-color">{{ $category->category_project }}</h3>
<div class="bigBox">
<div class="container1">
#foreach($projects as $project)
<article class="barghabi">
<a href="#" data-cat="news" data-state="vic">
<img src="{{ $project->image_project }}" alt="">
<h6 class="fnt_gh" style="line-height: normal;">
{{ $project->title_project }}
</h6>
</a>
</article>
#endforeach
<div class="content"></div>
</div>
</div>
</div>
#endforeach
And a categories table and a project table whose models and relationships are as follows:
class Project extends Model
{
protected $fillable = [
'title_project' ,
'period_project' ,
'description_project' ,
'manager_project' ,
'phone_project' ,
'email_project' ,
'image_project'
];
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
class Category extends Model
{
protected $fillable = ['category_project' , 'icon_project'];
public function projects()
{
return $this->belongsToMany(Project::class);
}
}
and pivot :
Schema::create('category_project', function (Blueprint $table) {
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->unsignedBigInteger('project_id');
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->primary(['category_id' , 'project_id']);
$table->timestamps();
});
controller:
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
$categories = Category::all();
$projects = Project::all();
return view('home.fa.pages.project.index', compact('categories' , 'projects' ));
}
}
You are calling #foreach($projects as $project) within your loop. You've defined $projects as all projects. Instead, use #foreach($category->projects as $project).
#foreach($categories as $category)
<div id="section-{{ $category->id }}" class="section">
<h3 class="fnt_gh fnt-color">{{ $category->category_project }}</h3>
<div class="bigBox">
<div class="container1">
#foreach($category->projects as $project)
<article class="barghabi">
<a href="#" data-cat="news" data-state="vic">
<img src="{{ $project->image_project }}" alt="">
<h6 class="fnt_gh" style="line-height: normal;">
{{ $project->title_project }}
</h6>
</a>
</article>
#endforeach
<div class="content"></div>
</div>
</div>
</div>
#endforeach
I'm not sure what's in $category->category_project but having a property with the same name as your pivot table is bound to create confusion. You should keep column names simple and readable, not append _project to each one!

Query AncestryOf with Laravel-nestedset in Laravel 5.8

I am using Laravel-nestedset and am having a hard time querying the ancestrosOf my category model.
This is what I am trying to do:
Works
http://carnival-experts.test/categories (this gives me a list of all categories)
http://carnival-experts.test/categories/carnival-games (this gives me a list of all Carnival Games)
Does Not Work
http://carnival-experts.test/categories/carnival-games/large-scale-games (this shows me a list of Carnival Games and not the Large Scale Games category)
I am sure this is just my lack of understanding--any help appreciated.
web.php
...
Route::get('/', 'CategoryController#index')->name('categories');
Route::get('/{category}/{slug?}', 'CategoryController#show')->name('show');
...
CategoryController.php
...
class CategoryController extends Controller
{
public function index()
{
$categories = Category::get()->toTree();
return view('categories.index', compact('categories'));
}
public function show(Category $category, $slug = null)
{
if (!is_null($slug)) {
$categories = Category::ancestorsOf($category);
return view('categories.show_subcategory', compact('categories', 'category', 'slug'));
} else {
return view('categories.show', compact('category'));
}
}
}
show_category.blade.php
...
#foreach($category['children']->chunk(3) as $chunk)
<div class="row">
#foreach($chunk as $category)
<div class="col-md-4" style="margin-bottom: 2rem">
<div class="feature-box center media-box fbox-bg">
<div class="fbox-media">
<a href="/categories/{{$category->slug}}">
<img class="image_fade"
src="https://*****.s3-us-west-1.amazonaws.com/{{ $category->photo }}"
alt="Featured Box Image"
style="opacity: 1;"></a>
</div>
<div class="fbox-desc">
<h3>{{$category->name}}</h3>
<span>Learn More</span>
</div>
</div>
</div>
Products
#if(count($category->products) > 0)
#foreach($category->products as $product)
{{$product->title}}
#endforeach
#endif
#endforeach
</div>
#endforeach
...

Display posts belonging to category in laravel

I am trying to get the posts that belong to each category, i had this working before but i can't seem to find what i have done wrong here.
I have a Post Table and a Categories Table
ROUTE
Route::get('articles/category/{id}', ['as' => 'post.category', 'uses' => 'ArticlesController#getPostCategory']);
CONTROLLER
public function getPostCategory($id)
{
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
$categories = PostCategory::all();
// return view
return view('categories.categoriesposts')->with('postCategories', $postCategories)->with('categories', $categories);
}
VIEW
#foreach($postCategories->posts as $post)
<div class="well">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placekitten.com/150/150">
</a>
<div class="media-body">
<h4 class="media-heading">{{ substr($post->title, 0, 50) }}</h4>
<p class="text-right">By Francisco</p>
<p>{{ substr($post->body, 0, 90) }}</p>
<ul class="list-inline list-unstyled">
</ul>
</div>
</div>
</div>
#endforeach
POST MODAL
public function postCategory()
{
return $this->belongsTo('App\PostCategory');
}
POSTCATEGORY MODAL
class PostCategory extends Model
{
// connect Categories to Posts tables
protected $table = 'post_categories';
// Category belongs to more than 1 post
public function posts()
{
return $this->hasMany('App\Post', 'post_category_id');
}
}
I can't see what i am doing wrong every time I go to a category it shows
Trying to get property of non-object
Any help will be much appreciated thanks
replace your lines:
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
with:
$postCategories = PostCategory::find($id)->posts;
Change your line in your PostCategoryModel to:
return $this->hasMany('App\Post', 'post_category_id','post_category_id');

Laravel 5.7 Comment count for different posts

I am stucked at point where i got comment count for posts but it shows count of all comments of all posts on every post. I would like to know how to output in blade comment count for post ID
here is controller:
$posts = $posts->orderBy("posted_at", "desc")
->paginate(config("blogetc.per_page", 10));
$comments = BlogEtcComment::all();
return view("blogetc::index", [
'posts' => $posts,
'title' => $title,
'comments' => $comments,
]);
blade:
#foreach($posts as $post)
<section class="blog_area p_120">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="blog_left_sidebar">
<article class="blog_style1">
<div class="blog_img">
<img class="img-fluid" src="blog_images/{{$post->image_large}}" alt="">
</div>
<div class="blog_text">
<div class="blog_text_inner">
<div class="cat">
<a class="cat_btn" href="{{$post->url()}}">{{$post->slug}}</a>
<i class="fa fa-calendar" aria-hidden="true"></i>{{$post->created_at}}
<i class="fa fa-comments-o" aria-hidden="true"></i> {{count($comments)}}
</div>
<h4>{{$post->title}}</h4>
<p>{!! $post->generate_introduction(400) !!}</p>
<a class="blog_btn" href="{{$post->url()}}">Lasīt vairāk</a>
</div>
</div>
</article>
</div>
</div>
</div>
</div>
</section>
#endforeach
//Quickfix:
//assuming your posts table is called posts and that in your blogetccomments table //you have a post_id column pointing to the original post. Try something like
$posts = DB::table('posts')
->leftJoin('blogetccomments', 'posts.id', '=', 'blogetccomments.post_id')
->selectRaw('posts.*, count(blogetccomments.post_id) as commentcount')
->groupBy('posts.id')
->get();
In your blade template, Access the comments count for each post, as follows..
#foreach($posts as $post)
...
{{$post->title}}...
{{$post->commentcount}}
...
#endforeach
You can use withCount() to get count of comments for a specific post :
$posts = $posts->withCount('comments')
->orderBy("posted_at", "desc")
->paginate(config("blogetc.per_page", 10));
Above would require you to have comments relation on your Post Model :
Post Model :
public function comments()
{
return $this->hasMany(BlogEtcComment::class);
}
BlogEtcComment Model :
public function post()
{
return $this->belongsTo(Post::class);
}
And then in blade :
#foreach($posts as $post)
<p>Post : $post->id</p>
<p>Comments : $post->comments_count</p>
#endforeach

Categories