Home > other >  How to make a CRUD for a PackageItem table and get the Item via foreignKey in another table? in Lara
How to make a CRUD for a PackageItem table and get the Item via foreignKey in another table? in Lara

Time:10-25

This is my Item model. I have made a function arrayPackageItemSelect that gets the id and equivalent it to the item name.

class Item extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'price',
        'itemdescription',
        'activeInactive'
    ];

    public function packageitems()
    {
        return $this->hasMany(PackageItem::class);
    }

    public static function arrayPackageItemSelect()
    {
        $arr = [];
        $items = Item::all();
        foreach($items as $item){
            $arr[$item->id] = $item->name;
        }

        return $arr;
    }

}

my PackageItem Model

class PackageItem extends Model
{

    protected $fillable = [
        'user_id',
        'item_id',
        'price'
    ];

    protected $table='packageitems';

    public static function itemModel()
    {
        return $this->belongsTo(Item::class);
    }

}

my PackageItem Controller (CREATE) and getting the Item ID from another table (Foreign key) so I can put a category for it.

    public function addPackageItem(Request $request)
{
        $user = Auth::user();
        $item = Item::arrayPackageItemSelect();

        echo $item; // when I echo this I get Array to Conversion String in POSTMAN

        $fields = $request->validate([
            'user_id' => 'required',
            'item_id' => 'required',
            'price' => 'required|numeric'
        ]);

        // // echo $items;

        $package = PackageItem::create([
            'user_id' => $user->id,
            'item_id' => $item,
            'price'=> $fields['price']
        ]);

        return response($package, 201);
        
    }

What I get when I echo the Items

enter image description here

The results I get from POSTMAN

POSTMAN

My Schema

enter image description here

This is where my reference is https://www.artofcse.com/learning/product-view-insert-update-delete

Can anybody help me what is wrong?

CodePudding user response:

In your controller (addPackageItem method):

$package = PackageItem::create([
            'user_id' => $user->id,
            'item_id' => $fields['item_id'],
            'price'=> $fields['price']
        ]);

Also, i think there is an error in your PackageItem model. belongsTo should not be called in a static method :

public function itemModel()
    {
        return $this->belongsTo(Item::class);
    }
  • Related