Home > Mobile >  How to use only one data from database table limit id 1 to use only in laravel
How to use only one data from database table limit id 1 to use only in laravel

Time:10-31

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. enter image description here

CodePudding user response:

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

CodePudding user response:

Extending Ronny Dsouza answer Use your controller as

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

CodePudding user response:

As stated in Retrieving Single Models / Aggregates you can use find() to get a model instance with a certain primary key:

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

CodePudding user response:

Use ->first() instead of get()->all() in your controller and you will be fine - this will pull the first record only.

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.

CodePudding user response:

Websitesetting::first();

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

CodePudding user response:

If you need only this one row then you can do ist with first().

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