Home > Blockchain >  i have try a lot of ways but the data from table in controller didn't pass to view
i have try a lot of ways but the data from table in controller didn't pass to view

Time:06-05

Laravel Framework 9.13.0

CategoryController

public function category()
{
    $cate = DB::table('category')->get();
     //this loop work in controller
    foreach ($cate as $cat) {
        echo $cat->CategoryName;
    }

    // this work
    // $test="showing data test";
    // return view('admin.category', compact('test'));

    return view('admin.category', compact('cate'));

    // return View::make("admin.category")->with(array('category' => $cat));

    // return View::make('admin.category')->with('category',$cate);

    // return view('admin.category', ['category' => $cate]);

    // return view("admin.category", $cate);

    // return view("admin.category");
}

category.blade.php

            @php($i=1);
            @foreach($cate as $category)
                    {{ i   }}
                    {{ $category->CategoryName }}
                    {{ $category->DateCreate }}
                    {{ $category->DateUpdate }}

            @endforeach
            @endphp

the result display like this:

CategoryName }} {{ $category->DateCreate }} {{ $category->DateUpdate }} @endforeach ?>

If i remove @php and @endPhp, the result display nothing.

CodePudding user response:

you just mixed up some things here. You can do it like this (not tested):

CategoryController.php

use App\Models\Category;

public function category()
{
    $categories = Category::all();
    return view('admin.category', ['cate' => $categories]);
}

category.blade.php

@foreach($cate as $category)
   {{ $category->CategoryName }}
   {{ $category->DateCreate }}
   {{ $category->DateUpdate }}
@endforeach

CodePudding user response:

You are not supposed to loop inside the controller,

  • bring the whole array to view return View('admin.category')->with('category',$cate);

  • loop the array inside the view.

  @if(count($cate) > 0):
     @foreach ($cate as $cate):
        // your code
     @endforeach
  @endif

  • Related