Laravel recursive relations and returning $this - php

I have navbar with unknown levels of industries which can have child industries and I want to write recursive relationship to get the top one and show it as Category. I tried this:
public function category()
{
if($this->parent_id == 0){
return $this;
} else {
$this->parent_industry->category();
}
}
But I keep getting
LogicException: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
How to write recursive relationship and return $this?

Try this relations:
public function children()
{
return $this->hasMany('App\MenuItem', 'parent_id');
}
public function parent()
{
return $this->belongsTo('App\MenuItem', 'parent_id');
}
public function getRoot()
{
$cur = $this;
while ($cur->parent) {
$cur = $cur->parent;
}
return $cur;
}

Hi you can do this in an easy rather than using while
public function children()
{
return $this->hasMany('App\MenuItem', 'parent_id');
}
public function parent()
{
return $this->belongsTo('App\MenuItem', 'parent_id');
}
public function root()
{
if ($this->parent)
return $this->parent->root();
return $this;
}
Using recursion it is much simpler.
Hope this helps.

Related

How to paginate for hasMany relationship in laravel (App\News::user must return a relationship instance)

I am not able to paginate in laravel in this situation
return $this->hasMany('App\News','category_id')->orderBy('id','desc')->paginate(20);
but says error. in controller I have also tried
$byCategories=Category::findOrFail($id)->paginate(20);`
it also says error.
help me.
My Model is
class Category extends Model
{
public function news()
{
return $this->hasMany('App\News','category_id')->orderBy('id','desc');
}
public function newsMany()
{
return $this->belongsToMany('App\News')->paginate(20);
}
public function user()
{
return $this->belongsTo('App\User');
}
public function getRouteKeyName()
{
return 'slug';
}
}
another model one is
class News extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function category()
{
return $this->belongsTo('App\Category');
}
}
my controller code is
public function byCategory($id)
{
$byCategories=Category::findOrFail($id);
return view('back-end/news/byCategory', compact('byCategories'));
}
Thank you so much.
Pagination is not done in the Model
it is to be done in the controller, For example remove (->paginate(20);) from here
public function newsMany()
{
return $this->belongsToMany('App\News')->paginate(20);
}
keep it only as
public function newsMany()
{
return $this->belongsToMany('App\News');
}
and call the pagination in controller when returning the view
$news=Category::findOrFail($id)->newsMany()->paginate(20);
return view('view name', compact('news'));

How can I filter this with eloquent

I try to filter SurveyQuestionnaire which have Answer = 'poor' and their Questionnaire have step = 'rating'.
I've tried to look through the documentation of Eloquent and I've found nothing help.
This is my models.
class Questionnaire extends Model {
...
public function surveysQuestionnaires() {
return $this->hasMany(SurveyQuestionnaire::class, 'question_id');
}
public function answers() {
return $this->hasMany(Answer::class, 'question_id');
}
public function questionnaires() {
return $this->hasMany(QuestionnaireTranslation::class, 'question_id' );
}
}
class SurveyQuestionnaire extends Model {
public function survey() {
return $this->belongsTo(Survey::class ,'survey_id');
}
public function questionnaires() {
return $this->belongsTo(Questionnaire::class, 'question_id');
}
public function answer() {
return $this->belongsTo(Answer::class, 'answer_id');
}
}
Well, the hasMany method returns query builder, so you can simply add some conditions:
public function surveysQuestionnaires() {
return $this->hasMany(SurveyQuestionnaire::class, 'question_id')->where('Answer', 'poor');
}
Also, you can read this link Constraining Eager Loads and add your conditions manually after taking an instance of your model:
$items = App\Questionnaire::with(['surveysQuestionnaires' => function ($query) {
$query->where('Answer', 'poor');
}])->get();

Laravel 5.4 can't get relation of elloquent model

I have filters which belong to filter groups
Filter.php:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Filter extends Model
{
public function group()
{
return $this->belongsTo('App\FilterGroup');
}
public function products()
{
return $this->belongsToMany('App\Product', 'product_filters');
}
public function categories()
{
return $this->belongsToMany('App\Filter', 'category_filter');
}
}
And categories which have many to many relationship with the filters
Category.php:
namespace App;
use App\Events\CategoryDelete;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $events = [
'deleting' => CategoryDelete::class
];
protected $table = 'categories';
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function parents()
{
$parentCategories = collect([]);
$parent = $this->parent;
while (!is_null($parent)) {
$parentCategories[] = $parent;
$parent = $parent->parent;
}
return $parentCategories->reverse();
}
public function products()
{
return $this->hasMany('App\Product');
}
public function filters()
{
return $this->belongsToMany('App\Filter', 'category_filter');
}
public function hasFilter($filter_id)
{
foreach ($this->filters as $filter) {
if ($filter->id == $filter_id) {
return true;
}
}
return false;
}
public function getFilterGroups()
{
$filterGroups = collect([]);
foreach ($this->filters as $filter) {
if (!$filterGroups->has($filter->group->id)) {
$filterGroups[$filter->group->id] = $filter->group;
}
}
return $filterGroups;
}
}
And in the category view I want to display the filters along with their filter group but when I try the following:
#foreach($category->filters as $filter)
{{ $filter->group->name }}
<br>
#endforeach
It throws the Trying to get property of non-object exception
Why can't I get the group of the filter?
I changed the group() method inside the Filter model to filterGroup and now when I call $filter->filterGroup it works fine. I dont know why, maybe group is some reserved word or something.

2 foreign keys on one column in laravel 5.2

here's my database schema
and I have these models:
Admin
User
Bet
Match
Team
I'm confused how to define the relationShip between matches and teams in models
here Is what I did till now...
User.php
public function bets()
{
return $this->hasMany('\App\Bet');
}
Bet.php
public function user()
{
return $this->belongsTo('\App\User');
}
public function match()
{
return $this->belongsTo('\App\Match');
}
Match.php
public function bets()
{
return $this->hasMany('\App\Bet');
}
//?????????????
Team.php
//?????????????
actually what I need Is the code that should be placed instead of //???... in both Team.php and Match.php so that I can easily do such things...
$team->matches();
$match->team1();
$match->team2();
thanks
It should be something like this:
Match.php
public function team1()
{
return $this->belongsTo('\App\Team', 'team1_id');
}
public function team2()
{
return $this->belongsTo('\App\Team', 'team2_id');
}
Team.php
public function matches()
{
return $this->hasMany('\App\Match', 'team1_id')
->orWhere('team2_id', $this->id);
}
You can specify which column should be targeted for each relationship:
public function team1() {
return $this->belongsTo('\App\Match', 'team1_id');
}
public function team2() {
return $this->belongsTo('\App\Match', 'team2_id');
}
Let me know if this helps.
It would be something like this. Give it a try.
Match.php
public function team1(){
return $this->belongsTo('App\Team', 'team1_id');
}
public function team2(){
return $this->belongsTo('App\Team', 'team2_id');
}
Team.php
public function matches1(){
return $this->hasMany('App\Match', 'team1_id', 'id');
}
public function matches2(){
return $this->hasMany('App\Match', 'team2_id', 'id');
}

Eager loading on polymorphic relations

class Admin {
public function user()
{
return $this->morphOne('App\Models\User', 'humanable');
}
public function master()
{
return $this->hasOne('App\Models\Master');
}
}
class Master {
public function admin()
{
return $this->hasOne('App\Models\Admin');
}
}
class User {
public function humanable()
{
return $this->morphTo();
}
public function images()
{
return $this->hasOne('\App\Models\Image');
}
}
class Image {
public function user()
{
return $this->belongsTo('\App\Models\User');
}
}
Now if I dump this:
return \App\Models\Admin::where('id',1)->with(array('user.images','master'))->first();
I get the perfect result one master, one user and one image record.
But if I do this
return $user = \App\Models\User::where('id',1)->with(array('humanable','humanable.master'))->first();
I only get one Admin record, the query get * from masters doesn't even run.
Any idea what I'm doing wrong, I'm sure this is possible.
If I remember correctly Laravel has lots of pitfall. You can try to use the protected $with var in Admin model instead of query builder with function.
class Admin {
protected $with = ['master'];
public function user() {
return $this->morphOne('App\Models\User', 'humanable');
}
public function master() {
return $this->hasOne('App\Models\Master');
}
}
In query builder, only need to include humanable. Now you should see master inside the humanable object.
return $user = \App\Models\User::where('id',1)->with('humanable')->first();
Hope this help.

Categories