0

This is my controller

function index()
    {
        $name_list = DB::table('customers')
            ->groupBy('first_name')
            ->get(); 
      $name_list2 = DB::table('customers')
      ->where('first_name', $name_list)->first();

     return view('dynamic_field')->with('name_list2',$name_list2); 
    }

This is my view i am retriving this in javascript.

@foreach($name_list2 as $name)
        '<option value="{{ $name->first_name}}">{{ $name->first_name }}</option>'+
        @endforeach
3
  • 1
    You are using first().It will take only one entry..So don't need to use foreach() in view.foreach used when you have a collection to print.. Commented Sep 30, 2019 at 5:54
  • but i have used foreach in view Commented Sep 30, 2019 at 6:04
  • check the answer..if you are passing $name_list to view,you could have to use foreach()..But in case of $name_list2 no need of foreach() Commented Sep 30, 2019 at 6:06

2 Answers 2

1

You don't need to foreach $name_list2 as this is a single record being fetched from the database as per your query.

You can try this without using foreach:

{{ $name->first_name}}

Hope it helps!

Sign up to request clarification or add additional context in comments.

7 Comments

i removed foreach but is not working '<option value="">{{ $name_list2->first_name}}</option>'+ but same error
What are you trying to achieve by this query? $name_list2 = DB::table('customers')->where('first_name', $name_list)->first();
i am trying to get dynamic dependent select box through query
I am not so sure about your requirements however the where() clause of your query isn't correct.
If you can show us your desired result, it will help.
|
0

You are using first().It will take only one entry..So don't need to use foreach() in view.foreach() used when you have a collection to print..

You can use $name_list2 as

@if(isset($name_list2))
  {{$name_list2->first_name}}
@endif

No need of foreach()

6 Comments

'<option value="">{{ $name_list2->first_name}}</option>'+ i used like this but same error
Use <option value="{{ $name_list2->first_name}}"></option>
This option value i am using in javascrtipt
can you check whether the value is coming to the frontend or not.
Try var option = "<option value='"+{{$name_list2->first_name}}+"'>"+{{$name_list2->first_name}}+"</option>"; Then append option to dropdown..` $("#district").append(option); `
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.