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);
Related
This is an array of data from the database. I want to show the name property from the array and This is also a laravel livewire project
how can I do this?
can I use it foreach loop?
*This is the Array
Illuminate\Database\Eloquent\Collection {#1431 ▼
#items: array:5 [▼
0 => App\Models\Reply {#1430 ▶}
1 => App\Models\Reply {#1429 ▼
#filleble: array:6 [▶]
#connection: "mysql"
#table: "replies"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▶]
#original: array:9 [▼
"id" => 4
"comments_id" => 1
"name" => "Md. Munirujjaman"
"email" => "mdmunirujjaman045#gmail.com"
"reply" => "dkjfdkj"
"notification" => 0
"status" => 0
"created_at" => "2021-01-12 03:01:47"
"updated_at" => "2021-01-12 03:01:47"
]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
}
**This is the Code of my project **
public $reply;
public function getModalId($item)
{
$this->reply = Reply::where('comments_id', $item)->orderby('id', 'desc')->get();
dd($this->reply);
}
I am trying to get this of my laravel project
and it give me the error message
ErrorException
Invalid argument supplied for foreach() (View:
#foreach($reply as $cmtReply)
{{$cmtReply->name}}
#endforeach
This is database data
how can I use this
{{$reply}}
return View:make('viewname')->with('reply', $this->reply);
#foreach ($reply as $CommentReply)
Hello, {{$CommentReply->name}}
#endforeach
You can access each property of any model by using the arrow -> followed by the name of the property. In your case, you want to access the "name" property, so you just type $myComment->name. See: https://laravel.com/docs/8.x/eloquent#retrieving-models
If you are using Laravels blade engine, you can use the same syntax within the {{ ... }} in your view.
To loop through a list of entities, you have to pass the variable which contains this list in your controller, when accessing the view. See: https://laravel.com/docs/8.x/views#passing-data-to-views
After that, you can access the variable with the name you gave to it in the passed array.
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 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')
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.