Laravel: Cannot get parent of a category - php

I am working on a classified ads platform and i am having a problem with a relation. Although i think i've set up everything right there is still this issue.
The scenario is this:
I have a model Category (App\Category) with the folowing relations to form the subcategories
class Category extends Model
{
public function parent() {
return $this->belongsTo('App\Category', 'parent_id');
}
public function children() {
return $this->hasMany('App\Category', 'parent_id');
}
public function adverts() {
return $this->hasMany('App\Advert');
}
}
I also have a model Advert (App\Advert) with the following relations
class Advert extends Model
{
public function category() {
return $this->belongsTo('App\Category');
}
public function user() {
return $this->belongsTo('App\User');
}
}
And finally I have a model User (App\Advert) with the following relations
class User extends Authenticatable
{
public function adverts() {
return $this->hasMany('App\Advert');
}
}
I am collecting the adverts in a collection within a controller like this
$adverts = $user->adverts()->with('category')->with('category.parent')->get();
The problem i am facing is when i try to output the adverts and the category they belong along with the corresponding subcategory i am experiencing this issue
Trying to get property of non-object (View:
..\resources\views\user\profile.blade.php)
On the following line
$ad->category->parent->name . ' / ' . $ad->category->name
When i dd the collection i can see all the adverts and the relations together with the category and the subcategory ... but when i try to output it like this i got this error Trying to get property of non-object
Help anyone?
Thanks

I am not sure if this helps anything, but I am posting it as an answer to make the code more readable, thats all. Not expecting any credits ;)
In one of my models I set up the child / parents relationships like this:
/**
* Get the Categories associated with the parent's `id`
*/
public function children()
{
return $this->hasMany('App\Category', 'parent_id', 'id');
}
/**
* Get the parent associated with the Category`s parent_id`
*/
public function parent()
{
return $this->belongsTo('App\Category');
}

Related

How to get a custom collection based on a data that is most repeated (from top to bottom))

I have a table like this:
Basically this table is named favourite_products and contains product ids that are added as favourite for users.
Now I wanted to get a collection of most added product from this table.
So in this case, a product with an id of 10 would be on top of the collection.
But I don't know how to get this collection ordering by from most repeated product id (prd_id)...
Here is the Model:
class FavouriteProduct extends Model
{
protected $table = 'favourite_products';
protected $fillable = ['usr_id','prd_id'];
public function user()
{
return $this->belongsTo(User::class, 'usr_id');
}
public function product()
{
return $this->belongsTo(Product::class, 'prd_id');
}
}
UPDATE #1:
Product.php Model:
public function favouritees()
{
return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
}
I think the following code solve your problem:
$most_liked_products = DB::table('favourite_products')
->select(DB::raw('count(prd_id) as total'), id)
->groupBy('total')
->orderByDesc('total')
->get();
Please try it and give your feedback
try use this
public function example()
{
$data=FavouriteProduct::orderBy('prd_id', 'ASC')->get();
dd($data);
}

Retrieving eloquent relationship with laravel

When I try to get the name of the Category from my product, I discovered I had to use a 'C' rather than a 'c' before it retrieved results. However when I try to get the Supplier name, the lowercase s works just fine. I was wondering what is causing this difference. Also if I dd($var), is the relations field expected to be empty. I assumed it would have something related to the relationships defined in my models.
Blade.php
<td>{{$product->Category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
Product.php
public function category()
{
return $this->belongsTo('App\Category','category');
}
public function supplier()
{
return $this->belongsTo('App\Supplier','supplier_id');
}
Category.php
public function product()
{
return $this->hasMany('App\Product');
}
Supplier.php
public function product()
{
return $this->hasMany('App\Product');
}
You're missing a _id on your Product model:
public function category()
{
return $this->belongsTo('App\Category','category_id');
}
Or leave empty
public function category()
{
return $this->belongsTo('App\Category');
}
In your Controller
public function index()
{
$products = Product::all()->with('category');
return view('your_view', compact('products'));
}
If you dd the products
In your View you will se that the relation has been loaded because of the
Eager Loading
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model.
#foreach($products as $product)
<td>{{$product->category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
#endforeach

getRouteByKeyName another model laravel

I have two models:
Categories
CategoriesTranslations
In model categories I writed:
public function getRouteKeyName(){
return 'alias';
}
Column alias belogns model CategoriesTranslations.
How I can return alias from model CategoriesTranslations?
My code is not working.
I tryed:
Add getRouteKeyName on CategoriesTranslations:
public function getRouteKeyName(){
return 'alias';
}
And in Categories add:
public function categoryTranslations() {
return $this->hasOne(CategoriesTranslations::class);
}
public function getRouteKeyName() {
return $this->categoryTranslations->getRouteKeyName();
}
I get error Call to a member function getRouteKeyName() on null When want show category by getRouteKeyName. How fix it?
You must use relationships between Categories and CategoriesTranslations.
In your Categories model:
public function categoriesTranslations()
{
return $this->hasMany(CategoriesTranslations::class);
}
public function getRouteKeyName()
{
$this->categoryTranslations->where('locale', Auth::user()->locale)->first()->getRouteKeyName();
}
Now you can call getRouteKeyName() from any instance of the Categories model and it will pull it from the CategoriesTranslations table.
** The potential fix here was adding in the where() statement and the first() method. Change the Auth::user()->locale to wherever you are storing which locale to use.

Laravel 5.1: Get only the records of the related model

I have three models:
Category
Post
Comment
These are their implementations:
class Category extends \Eloquent {
public function posts() {
return $this->hasMany('Post');
}
}
class Post extends \Eloquent {
public function category() {
return $this->belongsTo('Category');
}
public function comments() {
return $this->hasMany('Comment');
}
}
class Comment extends \Eloquent {
public function post() {
return $this->belongsTo('Post');
}
}
Is it possible, using eloquent, to get a list (array or collection) of all the comments (and only the comments, without posts) related to a Category?
(this means, given a category find all the related posts and then return all the related comments).
Thanks in advance!
Simply use hasManyThrough relation on your model Category :
class Category extends \Eloquent {
public function posts() {
return $this->hasMany(Post::class);
}
public function comments() {
return $this->hasManyThrough(Comment:class,Post::class);
}
}
After that, you can simply call $category->comments to have a Collection with all the comments related to a Category.
See https://laravel.com/docs/5.1/eloquent-relationships#has-many-through for extra information.
For Laravel 5.3 : https://laravel.com/docs/5.3/eloquent-relationships#has-many-through

Check if category belongs to post

Hello I'm trying to make script that show all categories and if category belongs to post this category should be checked with checkbox. My script wont works could you help me please. It shows only one checked category when have to shows two.
Controller Category model:
class Category extends Eloquent {
protected $table= "categories";
public function posts(){
return $this->belongsToMany('Post');
}
}
Post model
class Post extends Eloquent {
protected $table = 'posts';
public function categories(){
return $this->belongsToMany('Category');
}
}
catRelation:
[{"id":"45","post_id":"132","category_id":"1","created_at":"2014-12-26 20:32:41","updated_at":"2014-12-26 20:32:41"},{"id":"46","post_id":"132","category_id":"3","created_at":"2014-12-26 20:32:41","updated_at":"2014-12-26 20:32:41"}]
all categories: [{"id":"1","name":"Laravel","slug":"laravel","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"},{"id":"3","name":"PHP","slug":"php","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}]
A category shouldn't ever belong to a post, but rather a post should belong to a category.
I assume catRelation is your pivot table. It's worth nothing that you need neither id, created_at or updated_at for this.
Example models:
class Post extends Eloquent
{
protected $table = 'posts';
public function category()
{
return $this->belongsToMany('Category', 'catRelation', 'category_id');
}
}
class Category extends Eloquent
{
protected $table = 'categories';
public function post()
{
return $this->belongsToMany('Post', 'catRelation', 'post_id');
}
}
Note: I may have got the final arguments in belongsToMany the wrong way around.

Categories