How to solved in Laravel relations null value - laravel

Im tru to use to last version of laravel and i have small problem with Laravel relationship One to Many
Im try to connect products with categories
This is my code of Product model
public function categories()
{
return $this->belongsTo('App\Category');
}
this is my code of Category model
public function products()
{
return $this->hasMany('App\Product');
}
This is my code in controller
$products = Product::with('categories')->get();
dd($products);
this is my code from migration files
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('keywords')->nullable();
$table->string('price');
$table->text('description')->nullable();
$table->text('image')->nullable();
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
});
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('keywords')->nullable();
$table->timestamps();
});[![enter image description here][1]][1]
If someone know how to solved this problem I'll be very grateful

Firstly relation comes with eager loading.
Please update your codes according to single usage
In Product Model
public function category()
{
return $this->belongsTo('App\Category');
}
In Controller
$products = Product::with('category')->get();
dd($products[0]->category);

You are telling relationships name is categories, so laravel belongsTo will look categories_id instead category_id.
You can rename your relationships name as category() or
give your relationships foreign key to laravel like this;
return $this->belongsTo('App\Category', 'category_id', 'id');

Related

i am trying to get the name using a relationship

here what I am trying to get the name of the category by using a relationship
here so far what I have done is I have defined a relationship in my product model as such
Public function category()
{
return $this->belongsto(Category::class);
}
I have also stored the field category id
in my products table
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('Category_id');
$table->string('name');
$table->string('code');
$table->string('color');
$table->string('description');
$table->double('price');
$table->integer('quantity');
$table->string('image');
$table->timestamps();
});
also I have defined a relationship in my Category model such as
public function product()
{
return $this->hasmany(Product::class);
}
ALSO I HAVE DEFINED Relationship IN
PRODUCT AS
Public function category()
{
return $this->belongsto(Category::class);
}
in my view I am trying to get the name of the category
#foreach($products as $pro)
<tr>
<td><img src="{{asset('uploads/maj/'.$pro->image)}}" class="img-circle" alt="User Image" width="50" height="50"> </td>
<td>{{$pro->category->name}}</td>
<td>{{$pro->name}}</td>
<td>{{$pro->code}}</td>
<td>{{$pro->color}}</td>
<td>{{$pro->description}}</td>
<td>{{$pro->price}}</td>
<td>{{$pro->quantity}}</td>
I am receiving the error
Trying to get property 'name' of non-object
how can I get the name of the category ??
I am trying to get it like this but this is giving error
{{$pro->category->name}}
the category table row
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->String('Parent_id');
$table->string('name');
$table->string('status');
$table->timestamps();
});
my laravel version is 7 thanks
Maybe one or more product doesn't have category or category_id is wrong.
you can use condition to check if category is not exist:
{{$pro->category ? $pro->category->name : "no category"}}
or can simply using null coalescing operator:
{{$pro->category->name ?? "no category"}}
if category is required you should prevent it by add table relation/foreign.
try this
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->foreignId('category_id')->nullable()->constrained()->onDelete('cascade');
$table->string('name');
$table->string('code');
$table->string('color');
$table->string('description');
$table->double('price');
$table->integer('quantity');
$table->string('image');
$table->timestamps();
});
in model Product
public function category(){
return $this->belongsTo(Category::class,'category_id','id');
}
thin call products
$products = product::orderBy('created_at','asc')->with('category')->get();
you can chick if has relationship or not
#if(! empty($pro->category)) {{ $pro->category->name }} #else <span>no category</span> #endif
You should try like this way :
(!empty($pro->category)) ? $pro->category->name : 'No category found'
I think You should define foreign key properly because your category_id not follow the coding standard. if you Category Model are in App directory you can use pass namespace like this
Public function category()
{
return $this->belongsto('App\Category','Category_id','id');
}
other wise :
Public function category()
{
return $this->belongsto('App\Models\Category','Category_id','id');
}

Call to a member function post() on null on many to many relationship

I have created two table to store post information:
Posts table where I store overall information except categories.
Migration file of each table looks like this:
posts
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('slug');
$table->longText('excerpt');
$table->longText('description');
$table->tinyInteger('feature')->default(1);
$table->enum('status',['publish','draft']);
$table->string('image');
$table->timestamps();
});
post_categories
Schema::create('post_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id')->nullable();
$table->unsignedBigInteger('post_id')->nullable();
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('post_id')->references('id')->on('posts');
$table->timestamps();
});
Now, I have following function in PostCategory model:
public function post(){
return $this->belongsToMany(Post::class);
}
Now, when I try to fetch data using following:
\App\Models\PostCategory::find(5)->post()->orderBy('created_at')->get();
I get call to member function post() on null
What should I do to get post with the category 5?
You misunderstood some concepts.
Here your relationship is between post and categories.
In post Model
public function categories(){
return $this->belongsToMany(Category::class,'post_categories','post_id','category_id');
}
In the Category model
public function posts(){
return $this->belongsToMany(Post::class,'post_categories','category_id','post_id');
}
Now, You're free to access posts from category and categories from post.
$post = Post::with('categories')->where('id',5)->first();
By this, you'll get a post with its categories.
$category= Category::with('posts')->where('id',5)->first();
By this, you'll get category with its posts.
Check more detail how many to many work
Edit:-
If by using post you want to make a condition in the categories then.
$post = Post::with('categories')->whereHas('categories', function($q){
$q->where('id',5);
})->get();

Fetching Relationship Model Data

I have the Below Table Structure
Users table
id- integer
name-string
Casefiles table
id- integer
user_id- foreign_key
name-string
Followups table
id- integer
date- date
casefile_id-foreign_key
I'm using the below Relationship between this models
User.php
public function casefiles()
{
if ($this->hasRole(['sales_executive'])) {
return Casefile::where('user_id', $this->id);
}
}
Casefile.php
public function user()
{
return $this->belongsTo('App\User');
}
public function followups()
{
return $this->hasMany('App\FollowUp');
}
Followup.php
public function casefile()
{
return $this->belongsTo('App\Casefile');
}
I want to fetch Users followups directly. How can i achive this ?
you need to use hasManyThrough() in your User.php you can add this,
public function followUps()
{
return $this->hasManyThrough('App\FollowUp','App\Casefile');
}
then you can normally call the followups using User::with('followUps')->find(1)->followUps
I have noticed that you are checking role in your relationship $this->hasRole(['sales_executive'] this may occur error as you are not if the statement is false. I think you take another approached and handle that as well. for more information on hasManyThrough prefer this link
This should be the case for a HasManyThrough Relationship.
In your case it should be
// Followups migration
Schema::create('followups', function (Blueprint $table) {
$table->bigIncrements('id');
$table->date('date');
$table->unsignedBigInteger('casefile_id')->nullable();
$table->timestamps();
$table->foreign('casefile_id')
->references('id')
->on('casefiles');
});
// Casefile migration
Schema::create('casefiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users');
});
// User.php
public function followups() {
return $this->hasManyThrough(FollowUp::class, Casefile::class);
}
// YourController.php
$user = User::all()->first();
dd($user->followups);

Get results from pivot table based on the combination of two IDs in Laravel Project

Hey guys In a new project for a client I have to make a filtration system for books that have genres.
I've made a many to many relationship and a pivot table. So far I've made the form with check boxes, because the goal is to query a combination of two or more genres and show only the results that have all the selected genres.
My migrations are:
Schema::create('genres', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 40);
$table->timestamps();
});
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 125);
$table->timestamps();
});
Schema::create('book_genre', function (Blueprint $table) {
$table->increments('id');
$table->integer('genre_id')->unsigned();
$table->foreign('genre_id')->references('id')->on('genres')->onDelete('cascade');
$table->integer('book_id')->unsigned();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->timestamps();
});
My model is:
class Book extends Model{
public function genres(){
return $this->belongsToMany('App\Genre', 'book_genre');
}
}
This is my controller where I take the Get array with genre IDs:
class FilterController extends Controller
{
public function index()
{
$genreIds = Input::get('genres');
$books = Book::whereHas('genres', function($q) use ($genreIds){$q->whereIn('genres.id', $genreIds);})->orderBy('created_at', 'desc')->paginate(10);
}
return view('filter.index', compact('books'));
}
Here the problem is that it is not filtering the results by a combination of the genres, it is filtering them simply if they have one of the genres.
What should I change so I can query out only the matching books what have the listed genres?
$query = Book::with('genres');
foreach($genreIds as $genreId){
$query->whereHas('genres', function($q) use ($genreId){
$q->where('id', $genreId);
});
}
$filteredBook = $query->get();
I found the same solution in Stackoverflow

How to make relationship without using modelname_id in laravel?

I am trying to use one to many relationship for post and category.And for the database columns,If i use like this
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('category_id');
$table->timestamps();
});
in Post model
public function Category()
{
return $this->belongsTo('App\Category');
}
in category model
public function posts()
{
return $this->hasMany('App\Post');
}
Its working if i use above method like $table->integer('category_id').But i want to use custom name like
$table->integer('cat_id') without using category_id like
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('cat_id');
$table->timestamps();
});
.I am using laravel 5.4 and please help me out. Thanks.
If you check out Laravel's site on Eloquent: Relationships under One To Many relationships, you'll see:
Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method:
return $this->hasMany('App\Comment', 'foreign_key');
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
This is also the case for $this->belongsTo which is just an inverse One To Many relationship. So in your case:
return $this->belongsTo('App\Category', 'cat_id');

Resources