J
J
jazzus2019-03-04 20:36:19
Laravel
jazzus, 2019-03-04 20:36:19

How to automate checks for the existence of a record in a relationship?

Laravel. Ubuntu server. Model User. Associated with many models like so

public function files()
{
    return $this->hasMany('App\Models\File', 'user_id', 'id');
}

Any relationship. Type. Many to many, to many through, has one, and so on.
I want to automate the check for the presence of objects for related models. I do.
public function hasModel($model)
{
   return count($this->$model) > 0;
}

Checks such
if ($user->hasModel('files')) {
   ..
}

An error arrives on the production server.
count(): Parameter must be an array or an object that implements Countable

At the same time, there is no error on the localhost.
Threw such options
public function hasModel($model)
{
   return $this->$model()->exists();
   if (!empty($this->$model()->first())) {
   return true;
   } return false;
   return $this->$model()->first()->count() > 0;
   return count($this->$model) > 0;
}

What is the best way to check for the existence of a record in a relationship? Is it worth it to try to check for all relations with one method at all, or for each relation to prescribe its own separate check, and then which one?
Type
public function hasFile()
{
  // Что вы здесь обычно пишете?
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2019-03-04
@jazzus

Solution by Alexey Ukolov ,
Checks for relations:
for hasOne $this->file for hasMany $this->files->isEmpty()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question