Answer the question
In order to leave comments, you need to log in
Trees in Laravel, how to create an array?
The global task is to display a tree-like list of files.
There is a table with files file_contracts (id, contract_id, name, parent_id);
There is a table with contracts (id, name, date, executor)
Set up a connection in the contract model:
// список файлов к договору
public function files()
{
return $this->hasMany('App\FileContract');
}
public function show($id)
{
$contract=Contract::find($id);
// тут мне надо превратить $contract->files в массив, которые описан ниже
$files = array();
return view('contract.view')->with('contract',$contract)->with('files',$files);
$documents[0]=array(
'name' => 'File 1',
'id' => '2',
'child' => array(
'1' => array (
'name' => 'sub File 1',
'id' => '5',
'child' => array (
'1' => array (
'name' => 'sub sub file 1',
'id' => '12',
),
'2' => array (
'name' => 'sub sub file 2',
'id' => '1342',
)
)
),
'2' => array (
'name' => 'sub file 2',
'id' => '5',
'child' => array (
'1' => array (
'name' => 'sub sub file 1',
'id' => '12',
),
'2' => array (
'name' => 'sub sub file 2',
'id' => '1342',
)
)
)
)
);
Answer the question
In order to leave comments, you need to log in
As a result, for the time being I solved the problem as follows, added a new method in the Contract model, to which I feed the array obtained using the table connection:
public function makeContractFiles($array,$level) {
if(count($array)>0) {
foreach($array as $key => $value) {
// выполняем перебор массива и ищем все элементы уровня level
if($value['parent_id']==$level) {
// начинаем собирать новый массив
$files[]=array(
'name' => $value['title'],
'id' => $value['id'],
'child' => $this->makeContractFiles($array,$value['id']),
);
}
}
}
if(isset($files)) {
return $files;
} else {
return 0;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question