Home > other >  How Can i Skip Loop from a certain Elements In foreach
How Can i Skip Loop from a certain Elements In foreach

Time:08-02

I Have This Code

index.Blade.php:

<select name="category_id" >

       <optgroup label="من فضلك أختر القسم">

          @if($categories && $categories -> count() > 0)

     @foreach($categories as $category)

   <option
              value="{{$category -> id }}">{{NameByEnLanguage()}} 
// I Want To Skip NameByEnLanguage() Function From Loop
The Output Is 

Pyramid
Pyramid
I Didn't Want To Loop The NameByEnLanguage() Function

  </option>
       @endforeach
    
          @endif
   </optgroup>
    </select>

Controller:

    public function index() {

        $dufaultLang = get_dufault_lang();
$categories =
mainCategory::where(
    'translation_lang',

    $dufaultLang
)
    -> Selection()  // Select From Selection Scope
    -> get();       // Get Selection Data

return view(
    'admin.maincategories.index',
     compact('categories')
);
    }

NameByEnLanguage:

function NameByEnLanguage()
{


  return  $TsEns = mainCategory::where('translation_lang', 'en')->get('name');
    foreach ($TsEns as $TsEn) {
        return $TsEn->name;

    }
}

// i have two categories in $category Variable So When I Want To get the NameByEN From The Function It's Repeat Twice So I Want To Remove The Function From The Loop How Can I Make It Please?

CodePudding user response:

Loading the desired category name from the controller Controller:

public function index() {
        $dufaultLang = get_dufault_lang();
        $data['categories_count'] = mainCategory::where('translation_lang', $dufaultLang)->count();
        $categories = mainCategory::where('translation_lang', $dufaultLang)->Selection()->get();

        foreach ($categories as $category) {
            $data['categories'][] = array(
                'id' => $category['id'],
                'name' => $this->GetNameByLanguage($category['id'], $dufaultLang),
            );
        }

        return view('admin.maincategories.index', ['data' => $data]);
    }

    public function GetNameByLanguage($category_id, $language)
    {
        $TsEns = mainCategory::where('translation_lang', $language)->first();
        if ($TsEns->name == null) return "Null";
        else return $TsEns->name;
    }

Blade:

 <select name="category_id" >
        <optgroup label="Label text">
            @if($data['categories_count'])
                @foreach($data['categories'] as $category)
                    <option value="{{ $category['id'] }}">{{ $category['name'] }}</option>
                @endforeach
            @endif
        </optgroup>
    </select>
  • Related