Youssef Boudaya
Youssef Boudaya

Reputation: 997

Undefined index Laravel

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

Upvotes: 1

Views: 5068

Answers (3)

Md. Adil Hasan
Md. Adil Hasan

Reputation: 81

Use like the following:

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

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163948

Since Rolemodules has many RolefunctionsChange the code to:

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

Upvotes: 2

Nikola Gavric
Nikola Gavric

Reputation: 3543

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

Upvotes: 1

Related Questions