how to convert stdclass into string

- 1 answer

Ad

i want to make a two combo boxes in my project , when i'm trying to get the elements inserted in the other one it gives me an error like that : Object of class stdClass could not be converted to string how can i solve this problem ? this is the controller :

 public function getIndex(){
        $category=DB::table('categories')->get(['id','name']);
        $sub=DB::table('subcategory')->where('category_id','=',$category)->get(['id','name','category_id']);
        return view ('contents.in')->with('category',$category)
                                    ->with('sub',$sub);
    }
    public function postIndex(Request $request){
        $name=$request->input('name');
        $sub_id=$request->input('sub_id');
        $category_id=$request->input('category_id');
        DB::table('incategory')->insert(['name'=>$name,'sub_id'=>$sub_id,'category_id'=>$category_id]);
        return redirect('/in');
    }
Ad

Answer

Ad

Why Issue ? After getting $category

 $category=DB::table('categories')->get(['id','name']);

$category is an array

What You should do ? You can't just do foreach inside it or do join

Lazy Way : (foreach)

$sub = '';
foreach($category as $cat)
{
     $sub.=DB::table('subcategory')->where('category_id','=',$cat->id)->get(['id','name','category_id']);
}
return view ('contents.in')->with('category',$category)->with('sub',$sub);

Now $sub will have your expected result.

I am not sure about your table structure so just i just did a foreach ;) But i want you do use join

Recommendation :

  1. Use Eloquent

  2. Use Joins

Update :

Here is the fiddle that you require.

cars & phones are the two array that we pass from the controller

cars=new Array("Mercedes","Volvo","BMW","porche");
phones=new Array('Samsung','Nokia','Iphone');

populateSelect();

$(function() {

      $('#cat').change(function(){
        populateSelect();
    });

});


function populateSelect(){
    cat=$('#cat').val();
    $('#item').html('');


    if(cat=='car'){
        cars.forEach(function(t) { 
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='phone'){
        phones.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

} 
Ad
source: stackoverflow.com
Ad