Answer the question
In order to leave comments, you need to log in
Laravel one-to-many relationship how to access?
class department extends Model
{
public function User()
{
return $this->hasMany('App\User','departments_id','id');
}
}
class UserAll extends Model
{
protected $table = 'users';
protected $guarded = [];
public function department()
{
return $this->belongsTo('App\Department','departments_id','id');
}
}
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('names');
$table->string('description');
$table->string('logo');
$table->bigInteger('departments_id')->unsigned()->index();
$table->foreign('departments_id')
->references('id')->on('users');
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
class DepartmertController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$comments = \App\Department::all();
$departmens=$comments->User();
dd($departmens);
return view('department.index',compact('departmen','user'));
}
Answer the question
In order to leave comments, you need to log in
in Department
public function users() {
return $this->belongsToMany('App\User', 'user_department', 'departament_id', 'user_id');
}
$departaments = Department::with('users')
->get();
@foreach ($departaments as $departament)
@foreach ($departament->users as $user)
{{$user->name}}
@endforeach
@endforeach
You should listen to what you are told. And about the question $ comments is a collection and not a model instance, this is an error
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question