laravel getting error in one to manay relationship - php

I am trying to get record(one to many) from database. But it only provides me product table data not both
table structure
my model
namespace App;
use Illuminate\Database\Eloquent\Model;
class brand extends Model
{
protected $table="brand";
protected $primaryKey = 'brand_id';
public function product(){
return $this->belongsTo('App\product','brand_id','brand_id');
}
}
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
class BrandController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$val=brand::with('product')->find(5)->product;
foreach($val as $va){
echo print_r($val);
}
}
It provides me the record from product table but not from both the tables

You are fetching only product, remove the product part to get the both:
$val=brand::with('product')->find(5);
Then to get brand_name-
$brand_name = $val->brand_name;
foreach($val->product as $product){
$prod_fault = $product->prod_fault;
}
Don't forget as #alexey mezenin said, make your hasMany() relation in your Brand model like-
public function product(){
return $this->hasMany('App\product','brand_id','brand_id');
}

Since brand has many products and product belongs to brand, the relationship must be hasMany() and not belongsTo():
return $this->hasMany('App\product', 'brand_id', 'brand_id');

Product Model
public function brands()
{
return $this->hasMany(Brand::class);
}
Brand Model
public function product()
{
return $this->belongsTo(Product::class);
}
BrandController index method
public function index()
{
$brand = Brand::with('product')->find(1);
echo ($brand);
}
Out Put:
{"id":1,"name":"Toyota","product_id":1,"created_at":"2018-02-05 00:00:00","updated_at":"2018-02-05 00:00:00","product":{"id":1,"name":"Car","created_at":"2018-02-05 00:00:00","updated_at":"2018-02-05 00:00:00"}}
For further review
Guide for using Eloquent ORM with laravel by scotch.io
Another Link
Laravel Eloquent Relationships from laravel documentation

Related

delete with eager load in laravel

I'm trying to delete a collection but I want to delete the NFTs related to a collection as well. How do I do this?
‍‍This is my Nft model Nft.php
class Nft extends Model
{
use HasFactory,SoftDeletes;
public function collection()
{
return $this->belongsTo(Collection::class);
}
}
This is my collection model Collection.php
class Collection extends Model
{
use HasFactory, SoftDeletes;
public function nfts()
{
return $this->hasMany(Nft::class);
}
}
This is my COntroller CollectionController.php
public function deleteCollection(int $id):RedirectResponse
{
Collection::with('nfts')->find($id)->delete();
return redirect('/collections');
}
But it did not work!!!
pleas help me!!!!!
At user model:
public function collection() {
return $this->belongsTo(Collection::class)->withTrashed(); }
Keep in mind that the observer events are not fired if you use mass delete for example. In the case Collection::with('nfts')->delete(); it might not work.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Collection extends Model
{
/**
* The "booted" method of the model.
*
* #return void
*/
protected static function booted()
{
static::deleting(function ($collection) {
$collection->nfts()->delete()
});
}
}

Laravel RelationShips eloquent Laravel with ( 5 tables )

I have 5 tables
Products
-- Categories
--- SubCategories
---- Marks
----- Suppliers
I want to know how to make relationship
I have Product Model structure with :
namespace App\Models\Products;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [.... ];
public function categorie(){
return $this->belongTo(categories::class);
}
public function sub_categorie(){
return $this->belongTo(sub_categorie::class);
}
public function marks(){
return $this->belongTo(marks::class);
}
public function suppliers(){
return $this->belongTo(suppliers::class);
}
}
i want to know if it's correct ?
Another Question how would be looks other Model relationships such Suppliers, Categories, SubCategories ...
It depends on the cardinality and the foreign_keys that are involved.
Products
-- Categories
--- SubCategories
---- Marks
----- Suppliers
The context that you gave me, I'm guessing that each table depends on the previous one as showed in the context that you gave. If so, then you can do the following:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
protected $fillable = [.... ];
public function mark()
{
return $this->belongsTo(Mark::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Marks extends Model
{
protected $fillable = [.... ];
public function subCategorie()
{
return $this->belongsTo(SubCategorie::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
protected $fillable = [.... ];
public function categorie()
{
return $this->belongsTo(Categorie::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Categorie extends Model
{
protected $fillable = [.... ];
public function categorie()
{
return $this->belongsTo(Product::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [.... ];
}
For more in depht inormation, you can consult the section about relationshipts on laravel docs: https://laravel.com/docs/8.x/eloquent-relationships.
Please use the correct nomeclature of relationship's, instead of "categorie" write "category" in the function name, with that laravel will automaticaly recognise the foreign key.
Example:
public function category(){
return $this->belongTo(categories::class);
}
public function sub_category(){
return $this->belongTo(SubCategory::class);
}
public function mark(){
return $this->belongTo(Mark::class);
}
public function supplier(){
return $this->belongTo(Supplier::class);
}
Show me your models folder please if you have any problem .

To carry out CRUD operations for multiple tables in a single view

I'm on Laravel 8 with Livewire, currently have 3 models, Category, SubCategory and MenuItem for 3 tables. All the above models have separate livewire controllers and have the code for the CRUD operations respectively. I have separate views and routes to edit the above tables and they all have a eloquent relationship between each other. Now what I need to do here to is, I need to display all the three tables in a single view to carry out the CRUD operations.
I tried to achieve this by using the sub-view function, to pass the view and make the variables available to the specific view, but it didn't work out and I think it isn't the way to do it, was just trying to figure a workaround. I'm mentioning my models down below for referencing. Please help me with this. Thanks a lot for your time!
App\Models\Category
class Category extends Model
{
use HasFactory;
protected $table = "categories";
protected $fillable = ['sub_category_name'];
public function SubCategories() {
return $this->hasMany(SubCategory::class, 'category_id');
}
public function MenuItems() {
return $this->hasManyThrough(
'MenuItem::class',
'SubCategory::class',
'sub_category_id',
'category_id'
);
}
}
App\Models\SubCategory
class SubCategory extends Model
{
use HasFactory;
protected $table = "sub_categories";
protected $fillable = ['category_id', 'sub_category_name'];
public function Categories() {
return $this->belongsTo(Category::class, 'category_id');
}
public function MenuItems() {
return $this->hasMany(MenuItem::class, 'sub_category_id');
}
}
App\Models\MenuItem
class MenuItem extends Model
{
use HasFactory;
protected $table = "menu_items";
protected $fillable = ['sub_category_id', 'item_name', 'item_description'];
public function SubCategories() {
return $this->belongsTo(SubCategory::class, 'sub_category_id');
}
}
This is what I tried to achieve the said result. As I needed to include the view with the sub category table to the menu items table view. I made the variables available to that specific view.
Resources\Views\Livewire\Menu-Item
<div>
#include('livewire.sub-category')
</div>
App\Providers\AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use App\Models\SubCategory;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
View::composer('livewire.menu-item', function ($view) {
$view::with('sub_category_name', SubCategory::orderBy('sub_category_name')->get());
});
}
}
I managed to solve the above problem, using livewire's component feature. Created 3 separate component for 3 separate tables, and finally used all the three components in the master-menu.blade.php file. Working with livewire and laravel is a treat.

Using Eloquent to retrieve the parent category name?

i have a simple application for recursive hasMany relationship with unlimited subcategories
the code is running without a problem but it's not retrieving the parent category name or title.
when i tried to loop through the data coming from the DB it have the parent id but not the parent category name
i need to get the parent category name
here is the code for both controller and model
CategoryController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$parentCategories = Category::where('parent_id',1)->get();
return view('welcome', compact('parentCategories'));
}
}
?>
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $guarded = [];
public function subcategory(){
return $this->hasMany('App\Category', 'parent_id');
}
}
?>
You should create another relation in same Category model.
public function parent() {
return $this->belongsTo('App\Category', 'parent_id');
}
And retrieving parent model will be like that:
$subcategory->parent->title;

Laravel 5 Method [ALL] does not exist

I'm trying to make a CRUD application in Laravel 5 to better understand how a php platform work ( first time using one ), but I keep getting the "Method [all] does not exist." error and I can't understand what i'm doing wrong. I have a table named 'products' in Mysql and what I'm trying to do, is to list all the entry's from within the table. I also have an index.blade.php that I will post if needed.
ProductsController.php
class ProductsController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$products = ProductsController::all();
return View::make('products.index')->with('products', $products);
}
Products.php
class Products extends Eloquent
{
}
routes.php
Route::resource('/', 'ProductsController#index');
Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a $table property on your model. [Ref]
So, you should rename your Products.php to Product.php (or define the $table property on your model).
Then you can retrieve all products:
$products = Product::all();
Product.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
//
}
ProductsController.php
<?php namespace App\Http\Controllers;
use App\Product;
class ProductsController extends Controller {
public function index()
{
$products = Product::all();
return View::make('products.index')->with('products', $products);
}
}
Why you write ProductsController to access all() function. To access all() function you must call Product model.
ProductsController::all();
Example
Product Model
class Product extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'products';
}
Product Controller
class ProductController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$products = Product::all();
return View::make('products.index')->with('products', $products);
}

Categories