Search code examples
laravelahp

Laravel 5.5 - Save multiple data continiously from blade


I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :

public function create()
{
 $kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
 $kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
 return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}

and this is the blade code :

fields.blade

It will make the form appear as total of criteria#

The problem is, I can't save it all to database. How do I get it to do this?


Solution

  • Updated method in the controller to the following:

    public function create()
    {
    
        $kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
        $kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
    
        $data = [
            'kriteria1' => $kriteria1,
            'kriteria2' => $kriteria2
        ];
    
        return view('kriteria_kriterias.create')->with($data);
    }
    

    How to output in the blade file:

    {{ $kriteria1 }}
    {{ $kriteria2 }}
    

    Or you update the controller to pass the complete results:

    public function create($id1, $id2)
    {
    
        $kriteria1 = Model\Kriteria::find($id1);
        $kriteria2 = Model\Kriteria::find($id2);
    
        $data = [
            'kriteria1' => $kriteria1,
            'kriteria2' => $kriteria2
        ];
    
        return view('kriteria_kriterias.create')->with($data);
    }
    

    And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:

    @foreach($kriteria1 as $k1)
        {{ $k1 }}
    @endforeach
    
    @foreach($kriteria2 as $k2)
        {{ $k2 }}
    @endforeach'
    

    To accept multiple values dynamicaly in the controller you can try something like this:

    public function create($ids)
    {
    
        $results = collect([]);
    
        foreach($ids as $id) {
    
            $kriteria = Model\Kriteria::findOrFail($id);
    
            if($kriteria) {
                $results->put('kriteria' . $id, $kriteria);
            }
        }
    
        return view('kriteria_kriterias.create')->with($results);
    }    
    

    Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.