0

I'm a beginner in Laravel and I the following have migrations.

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('company_id')->unsigned();
    $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
    $table->boolean('enable')->default(0);
    $table->string('name', 120)->nullable();
    $table->string('surname', 120)->nullable();
    $table->string('email', 120)->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->boolean('enable_map')->default(0);
    $table->rememberToken();
    $table->timestamps();
    $table->engine = "InnoDB";
});

Schema::create('comments', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->Integer('rating');
    $table->text('content');
    $table->dateTime('date_time');
    $table->string('ip', 25);
    $table->engine = "InnoDB";
});

User.php

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function photos()
    {
        return $this->morphMany('App\Photo', 'photoable');
    }

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function hasRole(array $roles)
    {
        foreach($roles as $role)
        {
            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            } else {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }

        return false;
    }

    public function loginHistory()
    {
        return $this->hasMany('App\UserLoginHistory');
    }
}

Comments.php

class Comments extends Model
{
    protected $quarded = [];
    public $timestamps = false;

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

When I make this code:

Comments::where('content','LIKE','%'.$query.'%')->orWhere('id','LIKE','%'.$query.'%')->orderBy($sortColumn, $sortMethod)->paginate(25);

I don't have the info about the user. I have only values from comments. Why How can I get info about user, which add these comments? I would like to display a list of comments along with information about the user.

3 Answers 3

2

I haven't info about user. I have only values from comments. Why?

Because you are doing the query only on the model Comments

How can I get info about user, which add this comments?

Add with user to the query:

$comments_with_user_info = Comments::with('user')->where('content','LIKE','%'.$query.'%')->orWhere('id','LIKE','%'.$query.'%')->orderBy($sortColumn, $sortMethod)->paginate(25);

I would like to display a list of comments along with information about the user.

You can get the name in this way ( for example in blade):

@foreach($comments_with_user_info as $comment)
    {{ $comment->user->name }}
@endforeach
Sign up to request clarification or add additional context in comments.

Comments

2
  1. As a best practice, the class name should take the singular form of the table name. You can read about this at https://laravel.com/docs/5.8/eloquent#defining-models.

  2. You should be able to access the user() relationship by eager-loading it using with().

$comments = Comments::with('user')
                ->where('content','LIKE','%'.$query.'%')
                ->orWhere('id','LIKE','%'.$query.'%')
                ->orderBy($sortColumn, $sortMethod)->get();

                // or paginate method

  1. What you are retrieving is a collection. So you will have to loop through the comments to get the user object
foreach($comment in $comments){
    $userObj = $comments->user;
    $email = $userObj->email;
    //...etc here
}

2 Comments

The comment on auto-guessing table names is incorrect; Laravel knows not to append an s if the name ends in an s; valid example is Series; it doesn't look for seriess if you omit protected $table = "series";, but Series is both the singular and plural form. Everything else is correct, but somewhat already covered in porloscerros Ψ's answer. I agree it should be Comment and not Comments, but it still works in this form.
@TimLewis, thanks. that is good to know. I will edit my answer to remove the info regarding auto-gessing
-1

Comments::with('user')->where('content','LIKE','%'.$query.'%')->orWhere('id','LIKE','%'.$query.'%')->orderBy($sortColumn, $sortMethod)->paginate(25);

2 Comments

Don't post code-only answers; explain what the code does and why it works. And please format it correctly (4 spaces for a code block)
@trafficker, can you please confirm if the above solution works. Based on the code on your question, it shouldn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.