So i am working on a laravel project but I am stuck in this part:
I have a database with 2 Tables: ‘folder’ and ‘subfolder’
i have a working crud for both of them where i also included hasMany and belongsTo. This is so i can see the folder name in the subfolder view.
Now i want to make a button in the folder view so i can view all the subfolders that have the same ‘folder_id’ as ‘id’ on folder. i already have a button that redirects with a ‘id’ value, but i still see all the subfolders and not the subfolders where folder_id = id.
Folder table:
Schema::create('folder', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments("id")->unsigned(false);
$table->string('name');
$table->timestamps();
});
subfolder table:
Schema::create('subfolder', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments("id")->unsigned(false);
$table->string('name');
$table->unsignedInteger('folder_id')->value(11)->unsigned(false)->nullable();
$table->foreign('folder_id')->references('id')->on('folder');
$table->timestamps();
});
folder.index:
@foreach($folders as $folder)
<tr>
<td>{{$folder->id}}</td>
<td>{{$folder->name}} </td>
<td>
<a href="{{ route('admin.subfolder.index',$folder->id)}}" class="btn btn-primary">View {{$folder->name}}</a>
</td>
<td>
<a href="{{ route('admin.folder.edit',$folder->id)}}" class="btn btn-primary">Edit</a>
</td>
<td>
<form action="{{ route('admin.folder.destroy', $folder->id)}}" method="post">
@csrf
@method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
subfolder controller index:
$subfolders = Subfolder::with('folder')->get();
$folders = Folder::all();
return view('admin.subfolder.index', compact('subfolders', 'folders'));
If i need to add any information i will gladly do so!
2
Answers
For getting only the specific subfolders from a folderId you can apply a whereHas condition on the eloquent:
this will return only those subfolders who have matching folder ID.
I hope this will resolve your issue.
Change the function in your
Subfolder
controller: