Search code examples
phplaravelloopsforeachcode-duplication

How Can I Prevent Showing Duplicate In foreach loop At Laravel Blade File?


This is my view blade file:

1 And this is my table data:

2

This is my view code :

<form action="" method="post">
@csrf
@foreach($options as $opt)

 <label for="siteName">site name</label>
 <input type="text" id="siteName" name="siteName" value="{{$opt->o_name('siteName')}}">

 <label for="siteURL">site url</label>
 <input type="text" id="siteURL" name="siteURL" value="{{$opt->o_name('siteURL')}}">

@endforeach

 <input type="submit" value="save">
</form>

This is my controller code:

public function viewOptions()
{
    $options = Option::all();
    return view('view/options', compact('options'));
}

This is my class code:

protected $guarded = [];

public function o_name($val)
{
      $valss = DB::table('options')
                   ->select('o_value')
                   ->where('o_name', '=', $val)
                   ->first();
      return $valss->o_value;
}

I want to show once in view not duplicate Data and inputs form@ How can I do this? what's the problem with my cods?


Solution

  • I think because you use two input in your @foreach and your foreach loop 2 times..

    try this:

    <form action="" method="post">
    @csrf
    @foreach($options as $opt)
    
     <label for="{{ $opt->o_name }}">{{ $opt->o_name }}</label>
     <input type="text" id="{{ $opt->o_name }}" name="{{ $opt->o_name }}" value="{{ $opt->o_value }}">
    
    @endforeach
    
     <input type="submit" value="save">
    </form>
    

    Update:

    if you want to get specific rows, you can just get them you want then pass into view

    $options = DB::table('options')
                    ->where('o_name', 'siteName')
                    ->orWhere('o_name', 'siteUrl')
                    ->get();
    

    or wite query builder:

    $options = Option::where(function ($q) {
         $q->where('o_name', 'siteName')->orWhere('o_name', 'siteUrl');
    })->get();
    

    another way is using laravel Scopes