Retrieving a single value from belongsToMany relationship in blade template - laravel

I have created a model with a belongsToMany relationship. The model is Vendor and the relationship with Location. So, in my blade template, I would normally do something like this:
#foreach ($vendor->locations as $loc)
{{$loc-id}}
#endforeach
However, I would like to simply json_encode only the id values for each of the locations. If possible, I would like to do so without creating a loop. So, I know I can do this:
{{json_encode($vendor->locations)}}
But as you can guess, this dumps out JSON data of all of the fields in the locations table.
I know I can modify my relationship to only include the ID fields, but I do not want to do this because I want to use the relationship elsewhere.
Is there a way to just grab the ID fields using something like:
{{json_encode($vendor->locations->id)}}

You can pluck the 'id' and convert it directly to json.
{{ $vendor->locations->pluck('id')->toJson() }}
This requires that $vendor->locations is a Collection.

You can use Laravel's pluck and json methods:
{{ $vendor->locations->pluck('id')->toJson() }}
You can refer to the documentation for more information:
https://laravel.com/docs/8.x/collections#method-tojson

Related

Accessing Auth'd user data throughout

I am looking to access the Auth'd users' data throughout my views. This information needs to come from a DB query so I can join in various other tables to get the data I need.
The view structure I am working with is as follows: (layout->dashboard). "Layout" being the generic html bits, parent. and "dashboard" being the page specific content.
My first attempt at passing data from the controller to the view outlined that I was only able to access the variable from the child view (dashboard) and not (layout) which I did presume beforehand. My question is, what is the best way to pass around user data, from a DB query, to any view I need it in.
In this one scenario, it is using a peice of data to retrieve the users avatar in the nav bar, found in "layout".
Many Thanks,
Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:
php artisan make:auth
to make auth interface.
Check Laravel Doc:authentication
And then, try below...
Query DB like this...
//Controller
$users = DB::table('users')->get();
return view('layout', compact('users'));
After get the users collection, then send to view Blade(in the html file) like this...
//`Layout.blade.php` as View file like this..
<div class="container">
#foreach($users as $user)
{{$user->name}}
{{$user->"any you want"}}
#endforeach
</div>
#displaying-pagination-results
Enjoy coding~!! :)

October CMS overriding list query

In backend I have a list of records. And this list displays all records of this type. It is possible to override this query?
In controller I have Eloquent query and i grab some data from database,
and i set this data in $query_data variable. Howe push this data in list view?
unfortunately, I didn't get exactly your point of telling override query, if you mean that set some condition in fetching data from database in Eloquent you have to use where for example in the example below we have users which their gender is male:
$users=User::where('gender','male')->get();
for set more condition you can do like this:
$users=User::where([['gender','male'],['status',1]])->get();
and for showing the variable in your view you can use compact method:
return view('YOUR BLADE FILE NAME',compact('users'));
hope be helpful bro

Laravel: Use "where" in View?

Is it possible to use where in a view where I passed a collection toß
For example: I have a collection i pass to my view as $statuses.
Inside the view I want to filter the collection for statistic purposes:
Is it possible to do something like this?
{{ $statuses->where('category', '=', 'open')->count() }}
Yes, it's possible, because there are where() and count() methods for collections too.
You can see all available methods for collections here

Laravel passing variable from multiple models

I have 2 models
User
Customer
Each user hasMany customers (aka Accounts)
the user model has
public function customer() {
return $this->hasMany('App\Customer', 'id','customer_id');
}
but when i try to output this:
$user->customer->name
i get an error saying:
Undefined property: Illuminate\Database\Eloquent\Collection::$name
When i use this one, i get the entire customers record output in JSON.
$user->customer
So the relationship is working, but obviously i am missing something. I was sure this was the right way to do it. I swear this worked in Laravel4.2 but now that I'm in Laravel 5 it doesn't.
As the error and the below link says, It is returning a collection (hasMany) not a single object, you need to either loop over the collection or do direct access in the collection based on the index.
that is to say... does doing this work?..
$user->customer[0]->name
http://laravel.io/forum/04-10-2014-undefined-property-illuminatedatabaseeloquentcollectionitem
You should loop over customers, if you want display customers in laravel view you can do the following
#foreach
($user->customer as $cust)
{{$cust->name}}
#endforeach

laravel eloquent get related articles based on a tag

I'm a bit confused about how to do the following.
I have a table of articles and a table of tags with a many to many join and a pivot table between the two. I've got the relationships set up in the models
An articles can have more than one tag.
How can I easily(?) obtain a list of related articles for an article based on the tags attached to the current article.
I've tried querying from the tags side as follows:
foreach($article->tags()->get() as $tag) {
$relatedArticles .= Tag::with('articles')
->where('id','=', $tag->id)
->take(6)
->get();
}
This produces a nil response
I'm not sure about how to query from the articles to find articles with the tags dynamically.
So if an article has attached tag1 and tag2 I then want to retrieve all articles which have either tag1 or tag2 attached to them (ideally sorted on article date). The tags will be different for each article and may just be one or many.
Ideally i'd like to do this with an eloquent query but not essential - I'm not sure how to do in mysql either as a starting point.
Any help appreciated
Provided you are using Laravel 4.1, you can do something like this using the whereHas eloquent method:
$tag_ids = $article->tags()->lists('id');
$relatedArticles = Article::whereHas('tags', function($q) use ($tag_ids) {
$q->whereIn('id', $tag_ids);
})
->orderBy('created_at')
->take(6)
->get();
Breakdown
There's a few things going on here:
lists()
You can use the lists method on a select to get just a particular column, we're only concerned with the ID column in this case.
More info here: http://laravel.com/docs/queries#selects
whereHas()
We're using the new whereHas method which you can read.
More more about here: http://laravel.com/docs/eloquent#querying-relations
use()
Since the whereHas method accepts a closure (or 'anonymous function'), the function doesn't have any access to variables set externally, so we need to send them through to the function. We can do this with use.
More information here: http://www.php.net/manual/en/functions.anonymous.php

Resources