Reputation: 496
I am trying to execute a query using eloquent
, however it returns me an array
. What I want is to only get the string value
of my query.
This is what I get
[{"name":"hey"}] [{"name":"sdasdasd"}]
Here's my eloquent
query:
$categoryName = Category::select('name')->where('id', request('category'))->get();
$subCategory = Subcategory::select('name')->where('id', request('subCat'))->get();
Upvotes: 1
Views: 10131
Reputation: 1
$name = Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;
echo $name;
OR
echo Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;
Upvotes: 0
Reputation: 261
You can get the answer using
$name = DB::table('Category')->where('id','=',request('category'))->pluck('name')->first();
echo $name;
Upvotes: 0
Reputation: 133
If you take only name then follow the below code.
$categoryName = Category::where('id', request('category'))->first()->name;
$subCategory = Subcategory::where('id', request('subCat'))->first()->name;
echo $categoryName;
echo $subCategory;
If you take all columns in a row follow the below code:
$categoryName = Category::where('id', request('category'))->first();
$subCategory = Subcategory::where('id', request('subCat'))->first();
echo $subCategory->name;
echo $categoryName->name;
I hope this i may help you.Try this.
Upvotes: 0
Reputation: 151
There are so many ways to achive your goal.
Solutions
pluck()
.$categoryName = Category::select('name')
->where('id', request('category'))
->pluck()
->first();
$categoryName = Category::find(request('category'))
->name;
Upvotes: 0
Reputation: 615
as per the Laravel Docs
Retrieving A Single Row / Column From A Table If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single stdClass object:
$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;
If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
so in your example maybe you need to do something like the following :
$subCategory = Subcategory::select('name')->where('id', request('subCat'))-> first();
echo $subCategory->name;
Upvotes: 3