将数据从数据库添加到laravel 5.4的索引页

时间:2022-04-14 07:44:23

I am trying to create an adverts section on my landing page of a laravel 5.4 project using data from a database but it is not working. in my welcome, I have added this lines of code

我正在尝试在laravel 5.4项目的登录页面上创建一个广告部分,使用来自数据库的数据,但它不起作用。在我的欢迎中,我添加了这行代码

    foreach($adverts as $advert)   {         
                 $advert;
                }

I have then created a WelcomeController with the following code

然后,我用以下代码创建了一个welcome econtroller

    namespace App\Http\Controllers;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Http\Request;

    class WelcomeController extends Controller
    {
/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
 {
    $this->middleware('auth');
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $adverts = DB::table('adverts')->get();

    return view('welcome', ['adverts' => $adverts]);
   }
}

This gives me an error $adverts is not defined What could I be doing wrong?

这给我一个错误$广告没有定义我做错了什么?

1 个解决方案

#1


2  

$adverts is not defined error is coming because you are missing echo or {{ $adverts->item }} in case of Laravel.

$广告没有定义错误,因为您缺少echo或{$广告->item},以防Laravel。

You need to echo $adverts data in foreach in your blade file in the below way:

你需要在你的刀片文件中以以下方式回应每个$ advertising数据:

@foreach($adverts as $advert)       
     {{ $advert->item }}
@endforeach

Or you can simply use PHP as well like below:

或者你可以简单地使用PHP,如下所示:

foreach($adverts as $advert){         
    echo $advert->item;
}

You can also convert your data to array and then display in foreach like below:

您也可以将您的数据转换为数组,然后在foreach中显示如下:

$adverts = DB::table('adverts')->get();
$adverts = json_decode( json_encode($adverts), true);

@foreach($adverts as $advert)         
    {{ $advert['item'] }}
@endforeach

You can first check what's coming in $advert array in the below way:

你可以先查看一下下面的广告中出现了什么:

echo "<pre>"; print_r($adverts); die;    

#1


2  

$adverts is not defined error is coming because you are missing echo or {{ $adverts->item }} in case of Laravel.

$广告没有定义错误,因为您缺少echo或{$广告->item},以防Laravel。

You need to echo $adverts data in foreach in your blade file in the below way:

你需要在你的刀片文件中以以下方式回应每个$ advertising数据:

@foreach($adverts as $advert)       
     {{ $advert->item }}
@endforeach

Or you can simply use PHP as well like below:

或者你可以简单地使用PHP,如下所示:

foreach($adverts as $advert){         
    echo $advert->item;
}

You can also convert your data to array and then display in foreach like below:

您也可以将您的数据转换为数组,然后在foreach中显示如下:

$adverts = DB::table('adverts')->get();
$adverts = json_decode( json_encode($adverts), true);

@foreach($adverts as $advert)         
    {{ $advert['item'] }}
@endforeach

You can first check what's coming in $advert array in the below way:

你可以先查看一下下面的广告中出现了什么:

echo "<pre>"; print_r($adverts); die;