I'm trying to get a single value from Query Builder in Laravel but the problem is I'm getting an array.
this is my query result in Postman with dd($myVar):
[{"is_liked":1}]
and also with echo($myVar):
Collection {#976
#items: array:1 [
0 => NewsCommentLike {#970
#fillable: array:3 [
0 => "user_id"
1 => "news_comment_id"
2 => "is_liked"
]
#connection: "mysql"
#table: "news_comment_likes"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:1 [
"is_liked" => 1
]
#original: array:1 [
"is_liked" => 1
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
]
}
and my code is:
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->get(['is_liked']);
How to get a single value from is_liked not an array?
This is why you have ->value('my_column') method. So you'll end up with:
NewsCommentLike::query()
->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])
->value('is_liked');
The advantage is that the value is retrieved directly from the database. If you call first() before it, it can be null thus break your code.
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->is_liked;
Calling first returns 1 result instead of an array, then you can call the column you want.
I believe you could also call it like this:
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->value('is_liked')
Related
I have the following eloquent in my controller,
$getJobs=JobTitle::where('department_id',DepartmentUser::where('user_id', $user->id)->first()->department_id)->get();
This gives me following collection
Illuminate\Database\Eloquent\Collection {#2970 ▼
#items: array:3 [▼
0 => App\JobTitle {#2967 ▶}
1 => App\JobTitle {#2968 ▶}
2 => App\JobTitle {#2962 ▶}
]
#escapeWhenCastingToString: false
}
And one model element looks like this
1 => App\JobTitle {#2968 ▼
#connection: "mysql"
#table: "job_titles"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:9 [▼
"id" => 898
"title" => "driver"
"company_id" => 635
"department_id" => 252
"created_by" => null
"created_at" => "2022-04-20 05:30:38"
"updated_at" => "2022-04-20 05:30:38"
"deleted_at" => null
"archived_at" => null
]
#original: array:9 [▶]
#changes: []
#casts: array:2 [▶]
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: array:3 [▶]
#guarded: array:1 [▶]
+archives: true
#forceDeleting: false
}
Now I want to store all the job title (title) value's into single array
"title" => "driver"
In the above scenario, I have array elements and therefore I need store all three respective job titles to one single array...
$jobs = ['driver', 'chef', 'engineer'];
I tried adding an foreach, but it was giving me the following error,
#foreach ($getJobs as $getJob)
dd ($getJob->title);
#endforeach
ParseError syntax error, unexpected token "foreach"
What is the best way to achieve this?
You can simply loop on $getJobs and collect the title names in an array like below:
<?php
$getJobs = JobTitle::where('department_id',DepartmentUser::where('user_id', $user->id)->first()->department_id)->get();
$titles = [];
foreach($getJobs as $job){
$titles[] = $job->title;
}
dd($titles);
I am creating a blog with posts in Laravel 5.2. Every post is going to have multiple tags. I created a relationship between posts and tags. When the post is created, I am trying to attach multiple tags to it.
Controller function
public function store(Request $request)
{
$attributes = [
'author_id' => Auth::user()->id,
'title' => $request->input('title'),
'text' => $request->input('text'),
];
$post = Post::create($attributes);
// Get the tag ids from the the tags table in the database
$tagsList = $request->input('tags');
$tags = explode(",", $tagsList);
$tagIds = array();
foreach($tags as $tag) {
$tagIds[] = Tag::select('id')->where('name', $tag)->limit('5')->get();
}
dd($tagIds); // Output below
$post->tags()->attach($tagIds); // not working
}
dd($tagIds) output
array:2 [▼
0 => Collection {#316 ▼
#items: array:1 [▼
0 => Tag {#317 ▼
#fillable: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:1 [▼
"id" => 32
]
#original: array:1 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
1 => Collection {#318 ▼
#items: array:1 [▼
0 => Tag {#319 ▼
#fillable: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:1 [▼
"id" => 36
]
#original: array:1 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
]
The returned array contains correct ids of the tags. I just do not know how to get them into a format, so that they can be passed to the attach method.
I would be very thankful for any kind of help!
For convenience, attach and detach also accept arrays of IDs as input:
$tagIds = array();
foreach($tags as $tag) {
$tagIds[] = Tag::select('id')->where('name', $tag)->first()->id;
}
dd($tagIds); // Output below
/*
Array
(
[0] => 1
[1] => 3
[2] => 5
)
*/
$post->tags()->attach($tagIds);
You can just use pluck to get the array of ids from collection, no need to loop to get the ids of tags.
example:
$tags = Tag::pluck('id');
$post->tags()->attach($tags);
Please also refer to the documentation
https://laravel.com/docs/9.x/collections#method-pluck
I'm trying to make it possible to display a certain record from my database, all of the other records from the table will work but one record.
Collection {#218 ▼
#items: array:2 [▼
0 => MenuItem {#219 ▼
+table: "MenuItem"
+primaryKey: "MenuItemCode"
#connection: "mysql"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▼
"MenuItemCode" => "fri"
"Gerechtcode" => "ha"
"SubgerechtCode" => "wh"
"MenuItem" => "Frikandel"
"Prijs" => "1.00"
]
#original: array:5 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => MenuItem {#220 ▶}
]
}
You can see here that all the records are getting displayed, the one in particular I need to use in my view is MenuItemCode.
public function bestellingShow($Tafel)
{
$bestelling = Bestelling::find($Tafel);
$gerecht = MenuItem::all();
$reservering = Reservering::find($Tafel);
return view('bestelling')->with([
'bestelling' => $bestelling,
'gerecht' => $gerecht,
'reservering' => $reservering
]);
}
This is my function used for what I'm trying to achieve. As you can see it retrieves all of the menuitems from the database and returns them with the view.
I'm expecting to make all of the records displaying inside my view, but instead of returning the MenuItemCode, it returns a "0" aka a null. What am I wrong?
I'm also using relations, but a kind of simular function I'm using is working using the same method.
i m a beginner at laravel. using 5.5 . i have this collection return by my controller :
$products = Product::with('bazar.resellers')->take(2)->get();
dd($products);
//return view('shop.index')->with('products', $products);
which basically is three tables with nested relations. Note the relations lists in the code below. i want to access data(all columns in red colour) from every model i have in the collection i.e. Product, bazar and reseller.
Relationships are quite fine. but how to retrieve it from a collection? i dunno how foreach loops play with a collection.
Collection {#578 ▼
#items: array:2 [▼
0 => Product {#487 ▼
#fillable: array:7 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▼
"id" => 1
"created_at" => "2018-04-27 12:54:41"
"updated_at" => "2018-04-27 12:54:41"
"imgp" => "shirt.jpg"
"title" => "shirt1"
"Prod_descript" => "shirt1 is a good shirt"
"price" => 10
"reseller_id" => 1
"City_id" => 1
"bazar_id" => 1
]
#original: array:10 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"bazar" => Bazar {#523 ▼
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▼
"id" => 1
"Bazarname" => "Saddar"
"Bazarlat" => null
"Bazarlong" => null
"created_at" => null
"updated_at" => null
"City_id" => 1
]
#original: array:7 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"resellers" => Collection {#574 ▼
#items: array:1 [▼
0 => Reseller {#564 ▼
#guard: "reseller"
#fillable: array:12 [▶]
#hidden: array:2 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:15 [▼
"id" => 1
"Fname" => "talha"
"Lname" => "ali"
"email" => "p#g.com"
"password" => "$2y$10$M7wOmSouxSAYADN7NeFdSObT8fGwkEOFxVmOgcNSWvrixWCDtA/1S"
"mobile_no" => "03169880008"
"landline_no" => "0987654"
"shop_name" => "MyTestSHop"
"NIC_no" => "170178359437589754"
"shop_address" => "University Town, Peshawar, Pakistan"
"remember_token" => "wrb3nOwOWQcTuoF0P9KnaknwpOxfpTHt4gkShUmTzkR2Df9A7pPY5shBq6pQ"
"created_at" => "2018-04-27 12:42:25"
"updated_at" => "2018-04-27 12:42:25"
"City_id" => 1
"bazar_id" => 1
]
#original: array:15 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▼
0 => "*"
]
}
1 => Product {#488 ▶}
]
}
the code i have tried is not working!
#foreach($products as $product)
<h1>{{ $product->title }}</h1>
#foreach($product->bazar as $bazar)
<h3>{{ $bazar->Bazarname }}</h3>
#foreach($bazar->resellers as $reseller)
<p>{{ $reseller->Fname }}</p>
#endforeach
#endforeach
#endforeach
If product has single bazar,then you don't need to use foreach on $product->bazar. You just need to use bazar property directly. and if product has many bazars, then update your product model bazar() method like:
public function bazars()
{
return $this->hasMany(Bazar::class);
}
It returns collection of bazars and then you can run loop on that.
I am new to laravel. I have written code like below. And when I add select, it causes an error saying undefined offset: 0.
It also causes same error when I have more than two records even though I commented out select part.
When I check the query using toSql(), it is perfectly fine.
So when I use dd() on $clientDrivers before return, the output is below. (Seems fine as well)
What would be the problem with my code?
Any suggestion or advice would be appreicated.
EDIT: I have found the problem which was the $appends in Driver Model. Why does $appends cause the problem?
Solution: I have fixed my Driver Model getBankAttribute which is used for $appends and it works fine.
Here is my code:
Model
public function drivers() {
return $this->belongsToMany('App\Model\User\Driver', 'ClientDriver', 'client_id', 'userdriver_id');
}
Controller
$client = ClientModel::findOrFail($id);
$select = ['UserDriver.name as userdriver_name', 'UserDriver.phone_number as userdriver_phone_number'];
$clientDrivers = $client->drivers()
->select($select) // this does not work. If this is commented out it works perfectly fine.
->get();
return response($clientDrivers, 200);
Result of dd($clientDrivers)
Collection {#805
#items: array:2 [
0 => Driver {#798
#dates: array:1 [
0 => "deleted_time"
]
#table: "UserDriver"
+timestamps: false
+appends: array:1 [
0 => "bank"
]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:2 [
"userdriver_name" => "driver1"
"userdriver_phone_number" => "140412351235"
]
#original: array:4 [
"userdriver_name" => "driver1"
"userdriver_phone_number" => "140412351235"
"pivot_client_id" => 1
"pivot_userdriver_id" => 1
]
#changes: []
#casts: []
#dateFormat: null
#dispatchesEvents: []
#observables: []
#relations: array:1 [
"pivot" => Pivot {#801
+pivotParent: Client {#713
#table: "Client"
#guarded: array:2 [
0 => "id"
1 => "created_time"
]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:20 [
"id" => 1
"created_time" => "2017-12-28 05:23:50"
"invoice_email" => ""
"biz_number" => "1234512345"
]
#original: array:20 [
"id" => 1
"created_time" => "2017-12-28 05:23:50"
"invoice_email" => ""
"biz_number" => "1234512345"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#forceDeleting: false
}
#foreignKey: "client_id"
#relatedKey: "userdriver_id"
#guarded: []
#connection: "mysql"
#table: "ClientDriver"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:2 [
"client_id" => 1
"userdriver_id" => 1
]
#original: array:2 [
"client_id" => 1
"userdriver_id" => 1
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: false
#hidden: []
#visible: []
#fillable: []
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
#rememberTokenName: "remember_token"
}
1 => Driver {#799
#dates: array:1 [
0 => "deleted_time"
]
#table: "UserDriver"
+timestamps: false
+appends: array:1 [
0 => "bank"
]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:2 [
"userdriver_name" => "driver2"
"userdriver_phone_number" => "140412351236"
]
#original: array:4 [
"userdriver_name" => "driver2"
"userdriver_phone_number" => "140412351236"
"pivot_client_id" => 1
"pivot_userdriver_id" => 2
]
#changes: []
#casts: []
#dateFormat: null
#dispatchesEvents: []
#observables: []
#relations: array:1 [
"pivot" => Pivot {#803
+pivotParent: Client {#713}
#foreignKey: "client_id"
#relatedKey: "userdriver_id"
#guarded: []
#connection: "mysql"
#table: "ClientDriver"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:2 [
"client_id" => 1
"userdriver_id" => 2
]
#original: array:2 [
"client_id" => 1
"userdriver_id" => 2
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: false
#hidden: []
#visible: []
#fillable: []
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
#rememberTokenName: "remember_token"
}
]
}
You need to pass string in $select. You are currently passing array in it.
Change your $select as below:
$select = "'UserDriver.name as userdriver_name', 'UserDriver.phone_number as userdriver_phone_number'";
You could use with() to get associated drivers for a client
$client = ClientModel::where('id',$id)
->with('drivers:name,phone_number')
->get();
$clientDrivers = $client->drivers;
return response($clientDrivers, 200);