1

i always use this ugly code to get a single value from the database for a given id

for example here i want to get the number of visits for a website

// ============================================ getNumberOfVisits()
//  
//  website_name : ..
//  return the number of visits for a given website
//
private function getNumberOfVisits($website_name)
{
    $visits = Website::where('name', $website_name)->get(['number_of_visit']);
    return $visits[0]['attributes']['number_of_visit'];
}

is there another way to get a single value from the database for a particular column given a where statement?

2
  • why do you need another way? is this bad? Commented Jan 11, 2015 at 20:03
  • no, it's just too long, and i was wondering that it may be a better way to achieve the same result. Commented Jan 11, 2015 at 20:05

1 Answer 1

3

How about this?

$website = Website::where('name', $website_name)->first(['number_of_visit']);
return $website->number_of_visit;

Or even better:

$visits = Website::where('name', $website_name)->pluck('number_of_visit');

In case you want to know...

pluck() actually does the same as my first code example. Here's the source:

public function pluck($column)
{
    $result = $this->first(array($column));

    if ($result) return $result->{$column};
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well I like it more than something like getSingleValueFromFirstResult ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.