I am using Laravel-4 to build an application. I am trying to make the best use of Eloquent ORM. Currently I am displaying a list of db entries which all have a number of tags associated with them
To the right I display a grid of all the tags however it is showing duplicate tags. I would only like to show unique tags
This is my code:
<div class="tags-panel">
<div class="tags-title"><h1>Tags</h1></div>
<div class="tags-cloud">
#foreach(Tag::distinct()->get() as $tag)
<span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}}
#endforeach
</div>
</div>
Does Eloquent provide a way of only retrieving distinct entries from the db?
Try using Tag::groupBy('field_name')->get()
<div class="tags-panel">
<div class="tags-title"><h1>Tags</h1></div>
<div class="tags-cloud">
#foreach(Tag::groupBy('field_name')->get() as $tag)
<span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}}
#endforeach
</div>
</div>
To use the distinct()-function you have either have a select() in your chain, or use a field as an argument in your get()-function. For example:
$tags = Tag::distinct()->get(array('field'));
or
$tags = Tag::select('field')->distinct()->get();
You could also instead use groupBy('field') if you don't want to supply field names:
$tags = Tag::groupBy('field')->get();
Related
When I try to echo and display the output of a query in my dashboard it is appearing like this
[{"job_type":"Sales Manager"}]
The query is this:
->where('id',$userId)
->select('job_type')
->get();
To display it on the dashboard I am using this code
<div class="col-md-6 col-lg-2 col-xlg-3">
<div class="card card-hover">
<div class="box bg-cyan text-center">
<h1 class="font-light text-white"><i class="mdi mdi-view-dashboard"></i></h1>
<h5 class="m-b-0 m-t-5 text-white">{{ $jobType }}</h5>
<h6 class="text-white">Designation</h6>
</div>
</div>
</div>
How do I just get the result instead of the variable name along with the brackets?
You can use this query
->where('id',$userId)
->pluck('job_type')
->first();
You should print it like {{$jobType->job_type}} or {{$jobType['job_type']}} based on your return type.
->where('id',$userId)
->select('job_type')
->get();
This code will return Collection instance so you should either use first(); or you iterate over the variable. You probably try to get the user so you should use it like this:
$user = User::where('id', $userId)->first();
and use below code in your view
{{ $user->job_type }}
Or you can use
$user = User::find($userId);
My Tables:
kategoris table
id | kode_kategori | kategori_name |
items table
id | kategori_id | item_name
In items table the kategori_id column has foreignkey.
My Controller:
public function edit($id)
{
// $item = Item::findOrFail($id);
$item = DB::table('items')
->join('kategoris', 'items.kategori_id', '=', 'kategoris.id')
->where('items.id', '=', $id)
->select('items.*', 'kategoris.*', 'items.id', 'items.kategori_id')
->get();
// dd($item);
return view('master-dev/item/edit', compact('item'));
}
My View:
<div class="card card-default">
{{ Form::model($item,['route'=>['item.update',$item['id']], 'files'=>true,'method'=>'PUT']) }}
<div class="card-header">
<h3 class="card-title"><b>Edit Data Item</b></h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body">
#if(!empty($errors->all()))
<div class="alert alert-danger">
{{ Html::ul($errors->all())}}
</div>
#endif
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ Form::label('kode_kategori', 'Kode Kategori') }}
<select name="kode_kategori" id="kode_kategori" class="form-control">
#foreach ($item as $i)
<option valu="{{ $i['kode_kategori'] }}">{{ $i['kode_kategori'] }}</option>
#endforeach
</select>
</div>
</div>
..........
..........
{{ Form::close() }}
I've tried any solutions in stackoverflow such as adding (ifempty...) and other solution but still the result Undefined index: id in my edit blade. When I was trying using dd and vardump the results was shown. I need to loop the foreach in my dropdown menu to show the list of data from my categories table. And I need to join my items table and my categories table to get the name of the categories.
you are calling same id from items and kategoris try this
public function edit($id)
{
// $item = Item::findOrFail($id);
$item = DB::table('items')
->join('kategoris', 'items.kategori_id', '=', 'kategoris.id')
->where('items.id', '=', $id)
->select('items.*', 'kategoris.id as kategory_id', 'kategoris.kode_kategori', 'kategoris.kategori_name')
->get();
// dd($item);
return view('master-dev/item/edit', compact('item'));
}
if this answer doesnot work show your database relation i will give you solution
$item = ....->get() will return a Collection to only have one item you need to use $item = ....->first() instead
But since you have #foreach ($item as $i) I believe, you still want to have a collection, but in that case, your issue is here
{{ Form::model($item,['route'=>['item.update',$item['id']], 'files'=>true,'method'=>'PUT']) }}
Since you have a collection, we don't know what $item['id'] it's referring to. Perhaps $item->first()['id'] ?
I solved the problem, there's a conflict fetching data from items and kategoris tables. There are differences calling a value with array and object, mostly if its data looped. So in the controller I must declared one by one, the selected value id from kategoris table, and I have to join both tables to get the name of the kategoris, and then I have to declare once more to get the list of the kategoris data. So there are three (3) variables to declare each one of them. For this long time I was looking for the short code in my Controller but I cannot find it.
Thank you for all of you guys helping me this problem. Cheers.
How do you display results of many to many relationships and separate results regardless of their id?
#forelse ( $papers as $paper )
<article class="article-feeds mb-4">
#foreach ($paper->activityTypes as $actType )
<div class="flex ml-4" id="activitiesInformation">
<div class="flex-1">
<div>
<p class="font-bold">{{ $actType->activity_type }}</p> for {{ $paper->title }}
</div>
</div>
</div>
#endforeach
</article>
#empty
<p class="text-xl font-display">You don't have any activities listed for you</p>
</div>
#endforelse
I have a blade file that displays paper's activities, but what I need is to display each of them like in a separate activity feed, regardless of their id, as they are grouped by their paper_id key, I want it to be separated
For this example, I want to see
Recommendation for Expedita sit.
Publish Paper for Expedita sit.
to be separated from one another since they are different activity but they have the same paper id..
Furthermre,,
this is the activityTypes relationship, I'm talking about
/*success here.*/
public function activityTypes()
{
return $this->belongsToMany(ActivityType::class,
'paper_activities',
'paper_id',
'activity_type_id')
->withPivot('creator_id','display_name','body','status')
->withTimestamps() ;
}
I hope I get your idea. What you want is to get all the activity types related to a paper and each activity type on its own card.
To achieve that, from your Controller you can pass a new variable called $activity_types that you will fill like this:
//assuming you are returning it from the index method
public function index()
{
$papers = Paper::all();
$activity_types = $papers->flatMap->activityTypes;
return view('papers.index')
->with('activity_types', $activity_types);
}
also your blade should look something like this
#forelse ( $activity_types as $activity_type )
<article class="article-feeds mb-4">
<div class="flex ml-4" id="activitiesInformation">
<div class="flex-1">
<div>
<p class="font-bold">{{ $activity_type->activity_type }}</p> for {{ $activity_type->paper->title }}
</div>
</div>
</div>
</article>
#empty
<p class="text-xl font-display">You don't have any activities listed for you</p>
#endforelse
Make sure you have a relation to Paper from the ActivityType model.
I have a form on my website, which has required fields, and non required fields. The user fills in there details and submits the form. This is then emailed to the owner, and the data is then presented in a table.
However is it possible to show only the data that has been filled in and then remove the fields where no data was entered.
So far I have:
Blade Template:
div class="col-md-6">
<div class="row">
<div class="col-md-6">
<p><b>First Names</b></p>
</div>
<div class="col-md-6">
<p>{{ $first_names }}</p>
</div>
</div>
Which is then sent and is outputted as a table below:
<?php
if (!empty($titles)) {?>
<td class="tg-031e">Title:</td>
<td class="tg-031e">{{ $titles }}</td>
<?php }
?>
But I am assuming an else or else if statement would be required. So how would I have it so that only the fields that where filled in where shown in the table please.
Thanks
If you want to return nothing when there is no title the code below shoud make it work.
#if (isset($titles))
<td class="tg-031e">Title:</td>
<td class="tg-031e">{{ $titles }}</td>
#endif
Let me know if this worls :)
ps: #if(isset($titles)) does not work try #if($titles == NULL)
You can also try something like this:
http://laravel.com/docs/4.2/templates#other-blade-control-structures
Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. Basically, you want to do this:
{{{ isset($name) ? $name : 'Default' }}}
However, instead of writing a ternary statement, Blade allows you to use the following convenient short-cut:
{{{ $name or 'Default' }}}
I've been using eloquent in my models. I've got the following two tables:
Singlecard
->id
->card_id
Card
->id
->card_id
My Singlecard Model has the following function:
public function info()
{
return $this->hasOne('Card', 'card_id', 'card_id');
}
I used this to get the card (there's only one card in the deck for my test).
$cards = Singlecard::where('deck_id', '=', $deck)->get();
foreach ($cards as $card)
{
$cards_array[] = $card;
}
It got the correct card and using var_dump I verified that. However, here's the problem:
<div class="row singlecard">
<a class="" href="{{ $single->id }}">
<div class="large-2 columns">
<img src="{{ $single->info->card_image }}">
</div>
<div class="large-10 columns">
<div class="row">
<div class="large-12 columns">
<p>{{ $single->info->name }}</p>
</div>
</div>
<div class="row">
<div class="large-12 columns">
#foreach ($single->attributes as $attribute)
<p>{{ $attribute->alias }}</p>
#endforeach
</div>
</div>
</div>
</a>
</div>
Here's the twist: The attributes code works correct. It grabbed the correct attributes from a one to many relationship I defined. But it's grabbing the wrong info from the Cards table. Even though I defined the keys to match on, it is matching based on the ID of the singlecard and the card_id in the Cards table.
I've tried removing the keys and that didn't do anything. I even removed the function all together just to verify that that was the function being called. I'm not sure what's wrong?
UPDATE:
I figured it out, I did two things. One, I used id from the Cards table as the record to match with Singlecards. I also changed my function in the Singlecards model like so:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
This allowed me to properly query the relationship.
I needed to update how my models were related and better form the relationship. I also needed to change the model so that Singlecards belonged to Cards. I assumed it should be the opposite.
Cards contains all the info about the various cards and Singlecards is what is in each individuals hands/decks. I assumed that would make Singlecards the parent but that was a mistake. Once I changed the function in the model to be like this:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
Then it worked.