PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] Using Laravel with() and all()

 February 21, 2022     eloquent, laravel, php     No comments   

Issue

Currently I have this model called ProductLog.php

class ProductLog extends Model
{
use SoftDeletes, LogsActivity;

protected $table = 'product_logs';

protected static $logAttributes = ['name'];

protected static $logName = 'product_logs';

public function getDescriptionForEvent(string $eventName): string
{
    return "Product Log has been {$eventName}";
}

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'user_id',
    'product_id',
    'json_data',
    'type',
    'name',
    'is_active'
];

public function product()
{
    return $this->belongsTo('App\Services\Products\Product', 'product_id', 'id');
}
public function user()
{
    return $this->belongsTo('App\Services\Users\User', 'user_id', 'id');
}

}

and in query I'm using this command to get the data of my table ProductLog

public function fetchAll() 
{
    return $this->model->with('product','user')->get();
}

I'm using get(); on my query, is it possible to switch from get(); to all();


Solution

Short answer: no.

all() is a method on a Model, which returns a Collection, which doesn't have a with() method.

with() is a method on a Model, which returns a Builder, which doesn't have an all() method.

Because all() and with() are both Model methods, you can't chain them together.

with()->get() is the correct chain to use, and should give you the result you want.



Answered By - Joundill
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing