简体   繁体   English

如何仅使用数据库表中的一项数据限制 id 1 仅在 Laravel 中使用

[英]How to use only one data from database table limit id 1 to use only in laravel

I want to use my only one row from my database table.我想使用我的数据库表中的唯一一行。 Here is my model这是我的模型

class Websitesetting extends Model
{
    protected $table = 'websitesettings';
     protected $fillable = [
        'website_name', 'website_logo', 'locktimeout', 'email', 'address', 'mobile', 'fb_link', 'twi_link', 'yout_link','insta_link','linkdin','google_tag','website_logo2','favicon','footer_logo','footer_logo2'
    ];
}

Here is my controller这是我的控制器

public function home()
    {
        $websitesetting = Websitesetting::get()->all();
      
        return view('Frontend.welcome', compact('websitesetting'));
    }

Here is my database table, i want to use only one.这是我的数据库表,我只想使用一个。 在此处输入图片说明

public function home()
    {
        $websitesetting = Websitesetting::orderBy('id','desc')->limit('1')->get();
      
        return view('Frontend.welcome', compact('websitesetting'));
    }

Extending Ronny Dsouza answer Use your controller as扩展 Ronny Dsouza 答案 将您的控制器用作

public function home(websitesetting $websitesetting)
    {
        $websitesetting = Websitesetting::orderBy('id','desc')->limit('1')->get();
      
        return view('Frontend.welcome', compact('websitesetting'));
}

Use in your view在您的视图中使用

@if(!empty($websitesetting))
      @foreach($websitesetting as $sitesetting)
                        <a class="navbar-brand" href="{{('/')}}"><img src="{{ $sitesetting->website_logo }}" alt="{{ $sitesetting->website_name }}"></a>
                        @endforeach()
          @endif

As stated in Retrieving Single Models / Aggregates you can use find() to get a model instance with a certain primary key:检索单个模型/聚合中所述,您可以使用find()获取具有特定主键的模型实例:

public function home() 
{
  $websitesetting = Websitesetting::find(1);
  return view('Frontend.welcome', compact('websitesetting'));
}

Use ->first() instead of get()->all() in your controller and you will be fine - this will pull the first record only.在控制器中使用 ->first() 而不是 get()->all() ,你会没事的 - 这只会拉出第一条记录。

If you want to throw an error if there is no record found you can use ->firstOrFail() instead - this will throw 404 error if record not found.如果你想在没有找到记录的情况下抛出错误,你可以使用 ->firstOrFail() 代替 - 如果没有找到记录,这将抛出 404 错误。

Websitesetting::first();

或者

Websitesetting::find(1); // replace your id with 1

If you need only this one row then you can do ist with first().如果你只需要这一行,那么你可以用 first() 来做 ist。

public function home()
{
    $websitesetting = Websitesetting::first();   
    return view('Frontend.welcome', compact('websitesetting'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM