Select from two tables and show everything in laravel - php

I want to show on the page data from two tables but with a little condition and I can't figured it out how to make it in Laravel 4.
So I have table categories and table products. Currently I show all categories on the page and there is no problem. The problem is now there will have products without category and I want to loop them also on the page.
When admin create product he choose category but if doesn't choose any it will save 1 default in database products column single_product.
This is Product model
public function categories()
{
return $this->hasMany('Categories', 'category_id');
}
And Categories model
public function products()
{
return $this->hasMany('Product', 'category_id');
}
public function lowestProduct() {
return $this->products()->selectRaw('*, max(price) as aggregate')
->groupBy('products.product_id')->orderBy('aggregate');
}
And this is the view
<div class="col-xs-8 text-left" style="margin-top: 9px">
#if($category['no_category'] == 0)
Price: <strong>{{ $category->products()->min('price') }} $</strong>
#else
Price from: <strong>{{ $category->products()->min('price') }} $</strong>
#endif
</div>
How to select single column from products table and show them on the page along with categories name?

Then there is no category. Avoid your category class and just fetch directly from the product class. Create a function like:
public function singleItems()
{
return $this->where("single_product", 1)->get();
}
Then you foreach the result out. Please check this for further information:
https://laravel.com/docs/5.1/eloquent-collections
I know above is for another version of laravel than yours, but I think it should work. Else tell me, then I will look further.

Related

Get category name from category id through relationship. Laravel

I have looked through the forum, but the solutions I have seen so far, aren't aligning with the issues I'm getting, so, I was hoping someone more informed would help out.
So I have a Category modem and A post model and there relationship is as follows;
on post model:
public function postcategory(){
return $this->belongsTo(PostCategory::class);
}
on category model:
public function posts(){
return $this->hasMany(Post::class)->where('approved', 'true');
}
and I am using slugs to retrieve all the posts that belongs to a certain category slug, using this function:
public function cats($category){
$posts = PostCategory::where('category_slug', $category)->first()->posts;
$category = PostCategory::where('category_slug', $category)->first();
return view('posts', compact('posts', 'category'));
}
Now, I am trying to get the name of the category with the category id stored in the posts table. for example, if I have a category id of 1 and on the category table, if the id number 1 is PHP, how do I return the name PHP instead of the id 1?
Secondly, if I wanted to paginate the view where posts is being compacted to, how do I do that? I switched the code in the controller to this:
$posts = PostCategory::with('posts')->where('category_slug', $category)->paginate(15);
when I dd that line of code, it returns some values (with relations), but when I pass that to the view, I get errors.
Hopefully, someone see this and help me out. :D
on Category Model :
public function posts()
{
return $this->hasMany(Post::class);
}
On Controller :
public function cats($slug)
{
$category = PostCategory::whereSlug($slug)->firstorFail();
$posts= $category->posts()->where('approved', 'true')->paginate(15);
return view('category.show', compact('posts', 'category'));
}
On View :
#foreach($posts as $post)
$post->title
....
#endforeach
{{ $posts->links() }}

How to display the most recent single record in laravel using eloquent

How can i display the most recent single record in laravel using eloquent the solution i have shown below only shows the oldest record in the database not the most recent.
I have two tables a payments table and tenants table.
payments table has the following columns
id
amount
rent_from
rent_to
Payments table has a many to one relationship with the tenants table.
In my index page i wish to only display the latest payment per tenant (tenant_id)
In my controller i have
public function index() {
$payments = Payment::groupBy('tenant_id')->get();
return view('payments.index')->with('payments',$payments);
}
index.blade.php
#foreach ($payments as $post)
{{ $post->id }}
{{ $post->amount }}
{{ $post->rent_from }}
{{ $post->rent_to }}
{{ $post->tenant['name'] }}
#endforeach
This show the oldest record not the latest. How can i display the most recent payment record for each tenant - only one most recent payment record per tenant_id
you could make a new relation called 'lastPayment' by using 'hasOne' with orderByDesc to get the last payment ....
class Tenant extends Model
{
public function lastPayment()
{
return $this->hasOne(Payment::class,'tenant_id')->orderByDesc('payments.id');
}
}
public function index()
{
$tenants= Tenant ::with('lastPayment')->get();
return view('payments.index')->with('tenants',$tenants);
}
The following gives me the output i needed. Is there a more eloquent way of expressing this function.
{
$payments = Payment::whereRaw('id IN (select MAX(id) FROM payments GROUP BY tenant_id)')->get();
return view('payments.index')->with('payments',$payments);}
latest() is a function that will order by with the column you provide in descending order.
public function index()
{
$payments = Payment::groupBy('tenant_id')->get()->latest('id');
return view('payments.index')->with('payments',$payments);
}

PHP Laravel how to sort by using two tables

I have two MySQL tables in my Laravel-application, one called categories and the other called employees. The structure of the categories-table is:
id
category
order
and the employees table also has columns called:
id
category
order
So, lets say I have categories like: Consultants, Programmers and Administration and when I create an Employee in the backend I can assign the new employee to one of these categories. Now in the frontend of my Laravel-application I want the Employees displayed by the categories, and also the categories by order they are given. Let's say Consultants has order of 2, Programmers order of 1 and Administration order of 3.
Right now my controller looks like this:
use App\Employee;
class EmployeesController extends Controller
{
public function index()
{
$employees = Employee::all()->groupBy('category');
return view('app.employee.index', compact('employees'));
}
}
and my blade view file:
#foreach ($employees as $category => $workers)
<div class="col text-center mb-6">
<h2>{{ $category }}</h2>
</div>
<div class="row px-4 px-xl-10">
#foreach($workers->sortBy('order') as $worker)
// content of the employee
#endforeach
</div>
#endforeach
This sorts the employees correctly by simply using the categories of the Employees-table but with this I'm not able to sort by categories like I want to as described above.
So, can someone help me out?
EDIT
As an example I want the output look like this:
Programmers (since this category has order of 1)
// employees with category "programmers" here
Consultants (2)
// employees with category "consultants" here
Administration (3)
// employees with category "administration" here
To me you column definitions are a bit confusing, may I suggest a change to your columns:
Table 'categories'
------------------
id
name
order
Table 'employees'
-----------------
id
category_id
Add a foreign key to the employees table:
$table->foreign('category_id')->references('id')->on('categories')
And then your models could be mapped to each other with relationship methods:
class Employee extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
}
class Category extends Model
{
public function employees()
{
return $this->hasMany(Employee::class);
}
}
So with this in place we can simply query the database from the controller by:
use App\Category;
class EmployeesController extends Controller
{
public function index()
{
$categories = Category::orderBy('order')->get();
return view('app.employee.index', compact('categories'));
}
}
and display the results in your blade view:
#foreach ($categories as $category)
<div class="col text-center mb-6">
<h2>{{ $category->name }}</h2>
</div>
<div class="row px-4 px-xl-10">
#foreach($category->employees as $employee)
// content of the employee
#endforeach
</div>
#endforeach
I think you must change your query to :
$categories = Category::with(['employees'=>function($q){
$q->orderBy('order');
}])->orderBy('order')->get();

How to use eloquent to retrieve a column from another table

I have two tables
product: id|category ...
category: id|name ...
product.category is a foreign key linked to category.id . I am building a basic CRUD and I would like to display all Products in the the product table as well as the name of the category they belong to rather than their category ID. TO do this, while searching the laravel documentation I came across the query builder and I achieved my goal.
public function index()
{
$products = \DB::table('products')
->join('categories', 'products.category', '=', 'categories.id')
->select('*')
->get();
return view('product' ,compact('products'));
}
Under my models for product and category I have created the appropriate relationships.
product.php :
public function category()
{
return $this->belongsTo('App\Category');
}
category.php :
public function products()
{
return $this->hasMany('App\Product');
}
I keep hearing about the power of Eloquent and was wondering how I could achieve a similar result with eloquent and if eloquent is designed for such operations or if the query builder is the right way to go.
Every tutorial online seems to only use the post and comments scenario of getting all comments belonging to a post.
You can use this code
public function index()
{
$products = Product::with('category')->get();
return view('product' ,compact('products'));
}
In blade
#foreach($products as $product)
{{$product->name}}
{{$product->category->name ?? ''}}
//or
#if ($product->category)
$product->category->name
#endif
#endforeach
Also if in project table foreign key is not equal category_id. In your case
public function category()
{
return $this->belongsTo('App\Category', 'category');
}

Laravel 5 - Count the number of posts that are assigned to each category in a blog

I was wondering what the cleanest way was to count the number of posts that are connected to a category in my blog.
Here is how the table relationship is set up.
What I have is a hasMany relationship from the Category to the Post models like this:
In Categories Model
public function blog_posts()
{
return $this->hasMany('App\Http\Models\Blog_Post', 'category_id');
}
And in the Blog_Post Model
public function blog_categories()
{
return $this->belongsTo('App\Http\Models\BlogCategories', 'category_id');
}
In effect all I want to do is be able to return to my view the total number of posts that each category has as shown below. Where x is the number of posts within each category.
cat1 (x)
cat2 (x)
cat3 (x)
It's not hard to count I know however as I only want a count I do not want to also retrieve the records as they are not required and I also do not want to create more queries than is necessary.
I have not completed the view as yet but probably a start would be to pass through the categories in a loop to display each and add the count at the same time?
#foreach ($categories as $category)
{!! $category->name !!} - {!! Count of posts here !!}
#endforeach
Hopefully that is clear(ish)!
Eager load the relation in your controller:
public function index()
{
$categories = Category::with('blog_posts')->get();
return view('categories.index', compact('categories'));
}
You can then use the count() method on the blog_posts relation when looping over categories in your view:
#foreach ($categories as $category)
<li>{{ $category->name }} ({{ $category->blog_posts->count() }})</li>
#endforeach
EDIT: Since Laravel 5.3, you can use withCount() to load counts of relations, i.e.
$categories = Category::withCount('blog_posts')->get();
This will make the count available via a property:
foreach ($categories as $category) {
$blog_posts_count = $category->blog_posts_count;
}
The nicest way to do it with eager loading support I know is to create a separate relation with the post count. Check this out:
public function blog_posts_count() {
return $this->hasOne('App\Http\Models\Blog_Post', 'category_id')
->selectRaw('category_id, count(*) as aggregate')
->groupBy('category_id');
}
public function getBlogPostsCountAttribute() {
if(!array_key_exists('blog_posts_count', $this->relations))
$this->load('blog_posts_count');
$related = $this->getRelation('blog_posts_count');
return $related ? (int) $related->aggregate : 0;
}
Usage is simple:
{{ $category->blog_posts_count }}

Categories