Home > Software engineering >  @foreach php list object
@foreach php list object

Time:10-26

have now tried in 2 days to show the tables from the database (service_types) With now luck, im new to laravel but i have manage to fix mulltiple problems, but this is giving me a headache.

in the index i have this code:

<h3 >{{ trans('index.header_3') }}</h3>
<div  style="width: 100% !important">
            
@foreach($service_type as $index => $service)
<div  style="margin-left: 00px; margin-right: 00px width: 30%">
@if($service->image) 
<img src="{{$service->image}}" style="height: 50px" >
@else
N/A
@endif<br>{{ $service->name }}
</div>
@endforeach
</div>
</div>

but nothing is shown. Please help.

UPPDATE. I create one ServiceTypeController.php and add it in the controller folder.

i add this code:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\ServiceType;
use App\Http\Controllers\Controller;

class ServiceTypeController extends Controller {
public function index(){
$service_type = DB::select('select * from service_type');
return view('index',['service_type'=>$service_type]);
}
}

And in the web.php in routes:

Route::get('/','ServiceTypeController@index');

Still dont get any data on the page :(

CodePudding user response:

Use this when rotating the page in the Controller.

$service_type = "your db query";
return view('your-page', compact('service_type'));

You can also use commas to send more data to the view.

Example:

$service_type = "your db query";
$data1 = "aaa";
$data2 = "bbb";
return view('your-page', compact('service_type', 'data1', 'data2'));

CodePudding user response:

in PHP and many other languages, if array you are trying to loop over is empty, it will not do anything which might be what is happening in your code.

Try to debug your code by putting

{{ dd($service_type) }}

just before @foreach loop. Once php reaches dd() function, it will stop executing code and display content of that variable on screen.

  • Related