0
votes

i have 2 table that they have one to many relation and i want to get all client information and name user in blade

it is user model

 public function FirstClients(){

        return $this->hasMany("App\Models\FirstClient");
    }

it is client model

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

it is controller

   $allclients= DB::table('first_clients')->get();

        return view('admin.client.allclients' , compact('allclients'));

and this is blade

@foreach ($allclients as $client)
                        <tr>
                            <td>{{ $client->user->name}}</td>
                        <tr/>
@endforeach

and i have this error

Undefined property: stdClass::$user

2
can you elaborate on the question, which model or table you want to access is it, client or user. if you want to access through the client model then use eloquent queries with relation e.g: if I want to access the user model with relation of address then it should be like USERMODEL::with('relation_name')->get();Rushikesh Ganesh

2 Answers

0
votes

Your method name you are using is case sensitive. Try to use camelCase for relations in Models Now you have to change your method name to user()

Client Model

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

Blade View

@foreach ($allclients as $client)
  <tr>
    <td>{{ $client->user->name}}</td>
  <tr/>
@endforeach

Controller
You need to use eloquent to use relations.

$allclients= FirstClient::with('user')->get();

return view('admin.client.allclients' , compact('allclients'));
0
votes

You must use first_clients class to fetch data representation in model object Client e.g.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

    class FirstClient extends Model
    {
        /**
         * The table associated with the model.
         *
         * @var string
         */
        protected $table = 'first_clients';
    
    
        public function user(){
            return $this->belongsTo('App\Models\User');
        }
    
    
    }

In your controller

$allclients = FisrstClient::all();

return view('admin.client.allclients', compact('allclients'));