1

I am working on the access and permissions for users in my laravel project i want to display the function of the modules so i can add them to a certain role here is my database :

public function up()
{
    Schema::create('role_modules', function (Blueprint $table)
    {
        $table->increments('id');           
        $table->integer('rang');           
        $table->string('title');           
        $table->string('route');           
        $table->text('description');           
        $table->softDeletes();
        $table->timestamps();

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('role_modules');
}

public function up()
{
    Schema::create('role_functions', function (Blueprint $table)
    {
        $table->increments('id');           
        $table->integer('module_id')->unsigned();           
        $table->string('title');           
        $table->string('function');                
        $table->softDeletes();
        $table->timestamps();

        $table->foreign('module_id')->references('id')->on('role_modules')->onDelete('cascade');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('role_functions');
}

and here is my models code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Rolemodules extends Model
{
protected $table = 'role_modules';

public function func()

{
    return $this->hasMany('App\Rolefunctions','module_id');
}
}

When i want to display the functions of each module in my view like this :

@foreach($rolemodules as $rolemodule)
   {{$rolemodule->func['title']}}
@endforeach

I get this error: Undefined index: title

2
  • You need eager loading of eloquent model objects. Commented Feb 22, 2018 at 10:16
  • what does that mean ? Commented Feb 22, 2018 at 10:17

3 Answers 3

2

Since Rolemodules has many RolefunctionsChange the code to:

@foreach ($rolemodules as $rolemodule)
    @foreach ($rolemodule->func as $func)
        {{ $func->title }}
    @endforeach
@endforeach
Sign up to request clarification or add additional context in comments.

Comments

1

When you are returning the the collection back to the view you need to load the relationship like this:

$roleModel->load('func');

Then you can use it inside of your view like this:

@foreach($rolemodules as $rolemodule)
   @foreach($rolemodule->func as $obj)
      {{ $obj->title }}
   @endforeach
@endforeach

Comments

1

Use like the following:

@foreach($rolemodules as $rolemodule)
    {{$rolemodule->func->title}}
@endforeach

Comments

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.