how to make left join on two tables in laravel 5.4 - php

These are my two table's as:
company_industry_type:
law_master:
table company_industry_type has columns lm_id that is assigned to particular id.
i want to fetch the lm_id and law_name from table law_master
with respect to the lm_id assigned to id of table company_industry_type
please help me with this, i'm new to laravel.
<?php
$law = DB::table('tbl_company_industry_type')->pluck('lm_id');
$law_d = DB::table('tbl_law_master')->whereIn('id',$law)
->select('id','lm_id','law_name')->get();
$res_lms = '';
foreach($law_d as $law_details)
{
?>
<span id="sublaw_data">{{ $law_details->lm_id }}
({{ $law_details->law_name }}) <i class="fa fa-remove deleteclass"
onclick="delete_law('<?php echo $law_details->id?>')"></i></span>
<?php
$res_lms .=$law_details->id.",";
}
$res_lawids=trim($res_lms,',');
?>
my code returns only one id's data i.e 1 and not for 3,4 for last record of
company_industry_type

Using below query you can get result as per your requirements.
DB::table('company_industry_type')
->join('company_industry_type', 'company_industry_type.lm_id', '=', 'law_master.lm_id')
->select('law_master.lm_id', 'law_master.law_name', 'company_industry_type.*')
->get();

Related

Return data to the view in LARAVEL

So I do have a table "words" and it has 2 columns "word" and "countofletters"
When I get them in the controller, how can I return them to the view based on the count, basically the view should contain something like:
4 letter words:
1- climb
2- Play
3 letter words:
1- put
2- cut
And so on..
Return from controller
You can send data to the view with compact instruction :
$yourDataFetchedFromDB = "";
return view('myviews.view', compact('yourDataFetchedFromDB'));
In your view
You can now access the value of $yourDataFetchedFromDB in your view as if you were in your controller.
Now you can use something like :
<ul>
#foreach($yourDataFetchedFromDB as $row)
<li>$row->word</li>
#endforeach
</ul>
And to use count columns you can use :
$yourDataFetchedFromDB[0]->countofletters
Full view code
<h2>{{ $yourDataFetchedFromDB[0]->countofletters }}</h2>
<ul>
#foreach($yourDataFetchedFromDB as $row)
<li>$row->word</li>
#endforeach
</ul>
Note : Obviously you should check if $yourDataFetchedFromDB[0] is not empty before using it

How can limited span class item list in Laravel

Limit to item list:
More Description from the Pics:
I want to limited max item list at Laravel, As you if select all filter in admin panel, its look like this. So how can limited first 5 item to popular filters ?
<div class="g-attributes">
<span class="attr-title" style="color: orange"><b><i class="icofont-medal"></i> {{$translate_attribute->name ?? ""}}:</b> </span>
#foreach($termsByAttribute as $term )
#php $translate_term = $term->translateOrOrigin(app()->getLocale()) #endphp
<span class="item {{$term->slug}} term-{{$term->id}}" style="color: green" >{{$translate_term->name}}</span>
#endforeach
</div>
You can use the Collection's take() method to grab the first 5 elements:
#foreach($termsByAttribute->take(5) as $term)
Your question isnt very clear, but I am assuming that you want to be able retrieve the last 5 rows of the table, in your controller, you can get the records like this
$termsByAttribute = Table::latest()->take(5)->get();

How to comma separate properties from a Laravel returned object

First, my apologies if the issue has been resolved. I read a lot of similar posts, but not quite the right one for my case.
I am setting up a simple project in Laravel 5.8. I want to create a simple bookstore and I need a book to have multiple authors so each title is followed by the author, or authors - if many - separated by commas and the last one by the word 'and'.
I have set up two Models, 'Author' and 'Book' and their respective tables, as well as a pivot table since they are in a relation belongsToMany. Everything works like a charm, I get my results as expected. However, I cannot get to format the results as I need. In the case of multiple authors, I always get an extra comma in the end. Since I cannot get the commas right I haven't yet tried to add the last 'and' in the case of the last author.
In the case of a single author the solution is easy, I just use a conditional.
However in the case of multiple authors, thing get complicated.
The most popular method to similar problems was the use of implode() in various similar ways. The problem with this method is since Eloquent is using its internal logic to perform the query, when I loop through 'books', there is no author column, just a reference to the pivot table. In addition, the authors' include first name and last name in different columns. So, when I try to manually create an 'implodable()' array by fetching the respective data otherwise, I get double the item size, since each name consists of the first name and theist name. And on top of that, the whole thing runs inside a double loop, making things even more complicated for me.
I am sure there is a simple way around this.
This is a sample of my blade code as of now. Of course the conditionals should be rearranged accordingly when the problem will be solved, to implement the 'and' case:
<ul>
#foreach ($books as $book)
<li>{{ $book->title }} by
#if (count($book->author) == 1)
#foreach ($book->author as $name)
{{ $name->last_name }}
{{ $name->first_name }}
#endforeach
#else
#foreach ($book->author as $name)
{{ $name->last_name }}
{{ $name->first_name }}
{{-- print a comma here if there are other names, or an 'and' if it the last one. Problem seems that it needs to be solved outside the conditional, but how? --}}
#endforeach
#endif
</li>
#endforeach
</ul>
My DB structure:
'authors': 'id', 'last_name', 'first_name','created_at', 'updated_at'
'books': 'id', 'title', 'created_at', 'updated_at'
'author_book': 'id', 'author_id', 'book_id','created_at', 'updated_at'
Expected result:
Title 1, by Author 1
Title 2, by Author 1 and 2
Title 3, by Author 1, 2 and 3
Actual Result:
Title 1, by Author 1
Title 2, by Author 1 and 2 and
Title 3, by Author 1 and 2 and 3 and
If you didn't need the "and" mechanism, then implode with comma would do the job. For "and" mechanism use below code:
<ul>
#foreach ($books as $book)
<li>{{ $book->title }} by
#for ($i = 0; $i < count($book->author); $i++)
{{ $book->author[$i]->last_name }}
{{ $book->author[$i]->first_name }}
#if ($i == count($book->author) - 2)
and
#endif
#if ($i < count($book->author) - 2)
,
#endif
#endfor
</li>
#endforeach
</ul>
added non-breaking-space &nbsp wherever necessary to not get them linked to each other
Delete #if (count($book->author) == 1), if you use foreach inside.
You can't use #else, when before you close condition with #endif.
This #else has wrong construction, use #elseif instead.
If you want check authors count and show extra value, do it inside foreach with $book->author()->count().
What relation u have for book -> author? One book can have many authors or not?
Just display implode(', ', $book->author), based on your actual result you don't need to do complicated checking if/else anymore.
#foreach ($books as $book)
<li>{{ $book->title }} by {{print implode(', ', $book->author)}}</li>
#endforeach

Octobercms - Order frontend list by page variable (variable not on database)

So i'm trying to create a leaderboard with frontend user data on octobercms,
the leaderboard will be based on the sum of variables that are currently in the database. I've only recently started to look into twig and october, so please look at this patiently
The general Variable:
{% set totalScore = totalPoints + user.xp + user.progress %}
The List (simplified)
{% for user in activatedUsers %}
<div class="card">
<p class="name"><span class="rank-title">NAME</span><br>{{ user.name }}</p>
<p><span class="rank-title">LEVEL</span><br>{{ user.level }}</p>
<p><span class="rank-title">TOTAL POINTS</span><br>{{ totalPoints }} </p>
<p><span class="rank-title">PROGRESS</span><br>{{ user.progress }}</p>
<p><span class="rank-title">XP</span><br>{{ user.xp }}</p>
</div>
{% endfor %}
I can't really use the query to sort, since some variables are not in the database, but instead are being defined in the page.
I've looked into the sort twig function but i can't get it to work correctly.
I've tried this solution, but i get an exception.
I've added the following code in order for the "usort" function to work to the modules/twig/extension file but it did not work, and there has to be a simpler solution...
new \Twig_SimpleFilter('usort', array($this, 'usortFilter'))
public function usortFilter($item){
usort($item, function ($item1, $item2) {
if ($item1['orderNo'] == $item2['orderNo']) return 0;
return $item1['orderNo'] < $item2['orderNo'] ? -1 : 1;
});
return $item;
}
I've also tried the logical thing to do after reading the twig documentation:
{% for user in activatedUsers|sort('totalPoints') %}
But no luck there.
I can be walking in the wrong paths, so please feel free to suggest another or point out something i've missed.
Thanks in advance
Hmm i am not sure where you are setting your activatedUsers but before set that you can simply define this loop to sort them
you should use this only if your dataset is limited in numbers like 10 or 30 entry in list, no more then that its not efficient to sort db records in code
$activatedUsers = <<some code to fetch users>>
$sortedPointsWithUserId = [];
$sortedActivatedUsers = [];
foreach($activatedUsers as $user) {
// if $totalPoints is page variable you can use it directly $this->page['totalPoints'] from components and from page lifecycle $this['totalPoints']
$sortedPointsWithUserId[$user->id] = $totalPoints + $user->xp + $user->progress;
}
// sort array in descending order as we are storing totalpoints as value and key as user ID
// arsort maintain key value association
arsort($sortedPointsWithUserId);
foreach($sortedPointsWithUserId as $key => $value) {
$user = $activatedUsers[$key];
// create variable in model to hold totalPoints so we dont need to calculate again
$user->totalPoints = $value;
$sortedActivatedUsers[] = $user;
}
// $sortedActivatedUsers <-- this is your sorted array and you can use it
if you have any query please comment

Laravel 5.3 Blade foreach loop : show data in loop from two different database eloquent queries

I have two tables.
contenttype
content
contenttype returns me list of content types and I show them on page with foreach. e.g. Ambulance service, Blood Bank , clinic etc. as shown in snapshot.
At the same time I am fetching total number of contents of each type from another table(contents).
I was successful to get total number of contents of each type and show on the blade with foreach.
But situation is I want to show the number of contents on every content type.
Like this
Ambulance sevice 8,
Blood Bank 7,
Clinic 4.
My controller method is:
public function index()
{
if (Gate::allows('edit-content', auth()->user())) {
// below line returns list of content type e.g Ambulance service
$type = DB::table('contenttype')->distinct('label')->orderBy('label', 'asc')->paginate(10);
//below line counts the number of each content type e.g. Ambulance service 10.
$count = Content::selectRaw('type, count(*)total')->groupBy('type')->get();
return view('admin.content_listing', compact('type', 'count'));
} else {
abort(403, "Unauthorized");
}
}
This is blade code:
#foreach ($count as $c)
<span class="label label-danger">{{ $c->total }} </span>
#endforeach
This red number list is output:
#foreach ($type as $t)
<div class="list-group-item">
<a href="{{ route('content.type.listing', $t->type ) }}" > {{ $t->label }}
<span class=" pull-right glyphicon glyphicon-search"></span></a>
<span class="col-md-1 glyphicon glyphicon-plus-sign"></span>
</div>
#endforeach
Output is:
If I place above loop in second loop then Of course it will become nested loop that I don't want.
I need to show Ambulance 8,
Beauty clinic 8,
Blood Bank 1,
etc.
If anybody knows the solution kindly share it!
I have tried different ways but no success.
Rather than creating two queries and attempting to combine their results in the view, have you tried performing a join in a single query? Making certain assumptions about your column names and leaving aside the pagination, the actual SQL would be something akin to:
SELECT contenttype.*, count(content.id) FROM contenttype LEFT JOIN content ON contenttype.id = content.type GROUP BY contenttype.label ORDER BY contenttype.label ASC;
The code necessary to implement this query with Laravel's query builder functionality is pretty well documented in the documentation.

Categories