Undefined property: AppModelsProduct::$category Laravel 8

I am creating a simple inventory system using Laravel 8.
I want to join two tables: category and products

Category table:

id categoryname
1 drink
2 biscuits
3 toy

Products table:

id prodname catid
1 fanta 1
2 apple juice 1
3 buildblocks 3

I need the data passed to the table as the below output

id productname categoryname
1 fanta drink

While running the program I got the error as:

Undefined property: AppModelsProduct::$category

Category

class Category extends Model
{
    protected $fillable = [
        'id',
        'catname',
    ];

    public function products()
    {
        return $this->hasMany('AppModelsProduct', 'id', 'catid');
    }
}

Products
class Product extends Model
{
    protected $fillable = [
        'id',
        'prodname',
        'catid',
    ];

    public function category()
    {
        return $this->belongsTo('AppModelsCategory', 'category', 'id');
    }
}

view.blade.php
<html>
    <head>
        <body>
            <tbody>
                @foreach ($products as $key => $product)
                <tr>
                    <td>{{ $key }}</td>
                    <td>{{ $product->prodname }}</td>
                    <td>{{ $product->category->catname }}</td>
                </tr>
                @endforeach
            </tbody>
        </body>
    </head>
</html>

Controller
<?php

namespace AppHttpControllers;
use AppModelsCategory;
use AppModelsProduct;
use IlluminateHttpRequest;

class ProductController extends Controller
{
    public function view()
    {
        $products = Product::with('category')->get();
        $categories = Category::with('product')->get();
   
        return view('product.view')-> with([
            'products' => $products,
            'categories' => $categories,
        ]);
    }
}

Routes
Route::get('/products', [ProductController::class, 'view']);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You are mistaken in model here is an example
change catid to category_id
your colum in product table should be category_id in databsse to

In My user table

public function employee()
    {
        return $this->hasOne(Employee::class, 'user_id', 'id');
    }

Here is my employee table

public function user()
    {
        return $this->belongsTo(User::class);
    }

You have to work on you controller methods look here

 public function showEmployee()
    {
       
        $emps   = User::with('employee');
        
        return view('employee.show_emp', compact('emps'));
    }

Routes like this

Route::resource('showEmployee','<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7a28a97a488899395888b8b8295a7948f8890a28a978b889e8282">[email protected]</a>');

Here is an Your solution I am Trying to put my comfort.

Category

use AppModelsProduct;


class Category extends Model
{
    protected $fillable = [
        'id',
        'catname',
    ];

    public function products()
    {
        return $this->hasMany(Product::class, 'catid', 'id');
    }
}

Products

use AppModelsCategory;


class Product extends Model
{
    protected $fillable = [
        'id',
        'prodname',
        'catid',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

Controller

<?php

namespace AppHttpControllers;
use AppModelsCategory;
use AppModelsProduct;
use IlluminateHttpRequest;

class ProductController extends Controller
{
    



public function view()
    {
       
        $products = Product::with('category')->get();
        $categories = Category::with('product')->get();
        
        return view('employee.show_emp', compact('products', 'categories'));
    }
}

Routes

Route::get('products','<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68381a070c1d0b1c2b07061c1a0704040d1a281e010d1f">[email protected]</a>');

Add these both lines to your both models after namspace one of each
For Category
use AppModelsProduct;

For Product
use AppModelsCategory;

Note: this is untested code

Here i try to solve your problem

Method 2

The foreign key passed to the relationship is incorrect and the property you are trying to access in the view does not exist.

Please try out the following changes:

Products.php:

public function category()
{
    return $this->belongsTo('AppModelsCategory', 'catid', 'id');
}

view:
{{ $product->category->categoryname }}

One To Many (Inverse) / Belongs To

Method 3

Simple follow Laravel conventions and you avoid to your problems in the future.

https://github.com/alexeymezenin/laravel-best-practices#follow-laravel-naming-conventions

Table structure:

categories
    id - integer
    name - string

products
    id - integer
    category_id - integer
    name - string

Category model
<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Category extends Model
{
    protected $fillable = ['name'];

    public function products()
    {
        return $this->hasMany(Product::class);
    }
}

Product model
<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Product extends Model
{
    protected $fillable = ['name'];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

Routes
Route::get('products', [ProductController::class, 'index']);

Controller
<?php

namespace AppHttpControllers;

use AppModelsProduct;
use IlluminateHttpRequest;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::with('category')->get();

        return view('product.index', compact('products'));
    }
}

index.blade.php
<table>
    <tbody>
        @foreach ($products as $product)
            <tr>
                <td>{{ $product->id }}</td>

                <td>{{ $product->name }}</td>

                <td>{{ $product->category->name }}</td>
            </tr>
        @endforeach
    </tbody>
</table>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x