Get records based on days laravel carbon - mysql

I want to get the records based on days for example
1) > 180 days = number of records created
2) 90 to 180 days = number of records created
3) 60 to 90 days = number of records created
4) 30 to 60 days = number of records created
But I am not getting the exact result. Is this the correct way to do it?
what I have tried in the blade view
<?php
$date1 = \Carbon\Carbon::today()->subDays(180);
$date2 = \Carbon\Carbon::today()->subDays(90);
$date3 = \Carbon\Carbon::today()->subDays(60);
$date4 = \Carbon\Carbon::today()->subDays(30);
?>
in blade
{{ \App\Claim::where('created_at','>=', $date1)->count() }}
{{ \App\Claim::where('created_at','>=', $date2)->where('created_at','<', $date1)->count() }}
{{ \App\Claim::where('created_at','>=', $date3)->where('created_at','<', $date2)->count() }}
{{ \App\Claim::where('created_at','>=', $date4)->where('created_at','<', $date3)->count() }}
{{ \App\Claim::where('created_at','<=', $date4)->count() }}

Try this code
?php
$date1 = \Carbon\Carbon::today()->subDays(180)->format('Y-m-d');
$date2 = \Carbon\Carbon::today()->subDays(90)->format('Y-m-d');
$date3 = \Carbon\Carbon::today()->subDays(60)->format('Y-m-d');
$date4 = \Carbon\Carbon::today()->subDays(30)->format('Y-m-d');
?>
in blade
{{ \App\Claim::whereDate('created_at','>=', $date1)->count() }}
{{ \App\Claim::whereDate('created_at','>=', $date2)->whereDate('created_at','<', $date1)->count() }}
{{ \App\Claim::whereDate('created_at','>=', $date3)->whereDate('created_at','<', $date2)->count() }}
{{ \App\Claim::whereDate('created_at','>=', $date4)->whereDate('created_at','<', $date3)->count() }}
{{ \App\Claim::whereDate('created_at','<=', $date4)->count() }}
Note : Make variables date format Y-m-d

Related

How do I display my list view in recommended_items?

I'd like to show the list's introduction to users, and I've used the Association rule in Django for this project.
views.py
def user_detail(req, id):
AllParcel = Add_Parcel.objects.filter(id=id).first()
df = pd.read_csv('myapp/recommend.csv')
df = df.drop_duplicates().reset_index(drop=True)
df = df.pivot(index='item_id', columns='user_id', values='user_id')
df = df.notnull().astype(int)
frequent_itemsets = apriori(df, min_support=0.5, use_colnames=True)
rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.5)
user_loans = LoanParcel.objects.filter(user=req.user)
user_borrowed = [loan.parcel_item.name for loan in user_loans]
recommended_items = []
for item in rules['antecedents']:
if set(item).issubset(set(user_borrowed)):
recommended_items.extend(list(Add_Parcel.objects.filter(name__in=rules[rules['antecedents'] == item]['consequents'].tolist()[0])))
context = {
"AllParcel": AllParcel,
"recommended_items" : recommended_items,
}
return render(req,'pages/user_detail.html',context)
I wanted to render recommended_items to display similar to Add_Parcel using data from Add_Parcel's database to display, but when I put the display command in HTML, it returned as a blank value. How should I fix it?
user_detail.html
<h2>Recommended Items</h2>
<ul>
{% for parcel in recommended_items %}
<li>{{ parcel.name }} ({{ parcel.nametype }}) - {{ parcel.description }}</li>
{% endfor %}
</ul>
recommend.csv
item_id,user_id
1,1
1,2
1,3
1,4
1,5
1,6
1,7
3,8
3,9
3,10
3,11
1,12
1,11
1,10
2,9
2,8
2,7

How can i multiply data in nunjuncks?

for instance
<div class="price">{{blocks.quantity}} x {{blocks.price}} </div>
i want to multiply price by quantity
data from Json file.
var nunjucks = require('nunjucks');
var env = nunjucks.configure();
env.addFilter('mysum', function (arr) {
return arr
.map(e => e.quantity * e.price) // get amount to each e
.reduce((sum, e) => sum + e, 0) // calc total summa
});
var data = [
{price: 10, quantity: 2},
{price: 2, quantity: 7},
{price: 5, quantity: 11}
]
var res = env.renderString(`{{ data | mysum }}`, {data});
console.log(res);
There are multiple ways to do this, including building filters.
One simple way would be to define it in the template where you will use the value:
{% set total_price = blocks.quantity * blocks.price %}
You could then say:
I will sell you {{ blocks.quantity }} apples for {{ blocks.price }} each, the
total price will be {{ total_price }}.
You could also then use this in the logic:
{% if total_price > 100 %}
Price per apple is {{ blocks.price }}
{% else %}
Price per apple is {{ blocks.price * 0.9 }}
{% endif %}
Finally you can just express it like this {{blocks.quantity*blocks.price}}, as previous commenter Sauntimo said already.
You should be able to execute mathematical operations inside double curly braces like this:
<div class="price">{{blocks.quantity*blocks.price}}</div>
See the docs at https://mozilla.github.io/nunjucks/templating.html#math

Display time stored in database in HTML (django)

I'm building a bus booking website using Django. Users fill From, To, Bus type(ordinary or Volvo) and date. Results display the buses available on that route on that particular date. I made three tables - Bus, Route, and Frequency. You can check my models.py and views.py here - https://dpaste.de/Oi6a I convert the date to the corresponding day of the week. I have filtered out the buses, However, I want to display time on the template. This is part of my views.py code:
def select(request):
bus_type = request.GET.get('bus_type')
bus_from = request.GET.get('bus_from')
bus_to = request.GET.get('bus_to')
date_string = request.GET.get('date')
date = datetime.strptime(date_string, '%Y-%m-%d')
day = calendar.day_name[date.weekday()]
kwargs = { '{0}__range'.format(day): ["00:00:00", "23:59:59"],}
qs = Frequency.objects.filter(bus__type_of_bus=bus_type, bus__route__location_from=bus_from, bus__route__location_to=bus_to, **kwargs)
context = {'qs': qs, 'date':date_string,}
template = 'select.html'
return render(request, template, context)
As you can see qs filters the buses available and is then passed to the template. This is a part of the template:
<div id="pricing-table" class="clear">
{% for info in qs %}
<div class="price_block">
<h3>{{ info.bus.type_of_bus }}<span>{% if info.bus.type_of_bus == 'Volvo' %} Rs 550 {% else %}Rs 330 {% endif %}</span></h3>
Book
<ul>
<li><b>Bus Number -</b> {{ info.bus.bus_number }}</li>
<li><b>Route -</b> {{ info.bus.route }}</li>
<li><b>Date -</b> {{ date }}</li>
<li><b>Time -</b> {{ info.day }}</li>
</ul>
</div>
In the last line of this HTML file, I have added info.day. What I want is that this displays the time that bus operates on the given day. For example, If a person searches a bus on 29th April. 29th April will be converted to corresponding day i.e. Friday. The frequency table has 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' and 'Sunday' as attributes and these all are TimeField(). qs filters the buses and passes to the template. I want {{ info.day }} to show the time when the bus operates. Instead, it shows nothing. But when I change {{ info.day }} to {{ info.Friday}} it start showing the time. How can I display the time without having to manually go and change the day in {{ info.(here) }} every time I search for a bus. I didn't make it very clear, but I hope you understand. Let me know if you don't.
You can create a custom template tag do this for you and a method on the model.
I haven't tested this code, but this should work with or without small adjustments
Add this method to the Frequency model:
def get_day_info(self, date):
# Where date_string would be a datestring
date = datetime.strptime(date_string, '%Y-%m-%d')
day = calendar.day_name[date.weekday()]
info_time = getattr(self, '{}'.format(day))
return info_time
And register this as a template tag.
#register.simple_tag
def get_day_info(info, date):
return info.get_day_info(date)
You would call it in the template like this:
<li><b>Time -</b> {% get_day_info info {{ date }} %}</li>

Retrieving data from junction table via foreign key - Laravel

I'm trying to get data from a junction table and display it, so I have a users table and my junction table prescription_user. Prescription_user table has a user_id and prescription_id.
So what I'm trying to do is on this userdetails page, show all of this users prescriptions and access the prescription name and description etc, however when I try any of this I get "Trying to get property of non-object"
The models are set up to eager load correctly I think, the user model has a hasMany relation with the prescription_user model, and the prescription_user model has a belongsTo the user model.
Controller
function viewUserDetails($userId)
{
$logged_user_id = Auth::user()->id;
$user = User::find($logged_user_id);
$prescriptions = Auth::user()->prescription_user;
$fullname = $user->firstname ." ". $user->surname;
$email = $user->email;
$address = $user->address;
$postcode = $user->postcode;
$dob = $user->dateofbirth;
$uniquepatientnumber = $user->uniquepatientnumber;
$data = [];
$data['fullname'] = $fullname;
$data['email'] = $email;
$data['address'] = $address;
$data['postcode'] = $postcode;
$data['dateofbirth'] = $dob;
$data['uniquenumber'] = $uniquepatientnumber;
$data['prescriptions'] = $prescriptions;
return view('user/userdetails')->withData($data);`
userdetails blade
#extends('layouts.master')
#section('title', 'My Details')
#section('content')
<h1>My Details </h1>
<ul>
<li>Name: {{ $data['fullname'] }}</li>
<li>Email: {{ $data['email'] }}</li>
<li>Address: {{ $data['address'] }}</li>
<li>Postcode: {{ $data['postcode'] }}</li>
<li>Date of Birth: {{ $data['dateofbirth'] }}</li>
<li>Your Unique number is: {{ $data['uniquenumber'] }}</li>
<li>Your are currently prescribed {{$data['prescriptions']}}</li>
<p>Note: If you believe any of these are incorrect please contact a receptionist</p>
</ul>
#endsection``
There are some design flaws in what you have explained. You have a User model and a Prescription model. That means prescription_user is your pivot table (not junction table). If so far I'm correct, it means User and Prescription have a Many to many relationship. To prove my point, you said
Prescription_user table has a user_id and prescription_id.
That means prescription_user is the pivot table.
In your user model, define a many to many relationship with prescription. And vice versa.
User model
public function prescriptions() {
return $this->belongsToMany(Prescription::class, 'prescription_user', 'user_id', 'prescription_id');
}
Then you can change your controller function like this
public function viewUserDetails()
{
$user = Auth::user();
$prescriptions = $user->prescriptions;
return view('user/userdetails', compact('user', 'prescriptions'));
}
And your view
#extends('layouts.master')
#section('title', 'My Details')
#section('content')
<h1>My Details </h1>
<ul>
<li>Name: {{ $user->firstname }} {{ $user->surname }}</li>
<li>Email: {{ $user->email }}</li>
<li>Address: {{ $user->address }}</li>
<li>Postcode: {{ $user->postcode }}</li>
<li>Date of Birth: {{ $user->dateofbirth }}</li>
<li>Your Unique number is: {{ $user->uniquepatientnumber }}</li>
</ul>
Your are currently prescribed
<ul>
#foreach($prescriptions as $prescription)
<li>{{ $prescription->name }}
#endforeach
</ul>
<p>Note: If you believe any of these are incorrect please contact a receptionist</p>
#endsection
Your code would be neater and working great
Update
Getting data from the pivot table is relatively simple. Define those columns in the relationship
public function prescriptions() {
return $this->belongsToMany(Prescription::class, 'prescription_user', 'user_id', 'prescription_id')->withPivot('column1', 'column2');
}
In your view, you display it like this
{{ $prescription->pivot->column1 }} {{ $prescription->pivot->column2 }}
First I'm not sure that withData() is a thing. Just ->with($data).
Second, there is some confusion at the beginning of your function. You pass in a $userId, that you never use. Then you get the id from Auth::user(), then get a user with that id, which you already had. So just $user = Auth::user();
Third, you only get that error trying to use the -> operator on a non-object, and you only use it on $user-> and Auth::user()->
Since you got the user from Auth::user in the first place, I'm guessing it failed right out of the box at Auth::user()->id, and there is no Auth::user, but you would have to post a little more data, either from the error in the browser or from storage/logs/laravel.log.
BUT, if I use this code
Route::get('/', function () {
$user = \Auth::user();
die($user->name);
return view('welcome');
}
where there clearly is no Auth::user() (I haven't even got to a login yet) I get this output:
ErrorException in web.php line 16:
Trying to get property of non-object
1. in web.php line 16
2. at HandleExceptions-> ... array('user'=>null)
So it's probaby that.

Angularjs web app error

The angularjs app doesn't show me any result.
It shows me :
Name City Order Total joined
{{ cust.name }} {{ cust.city }} {{ cust.orderTotal }} {{ cust.joined }}
What is the reason of this type of error !!!
Update 1:
function CustController($scope)
{
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'},
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'},
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'}
];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
}
If you are using $scope approach, then you have to remove "cust." part from your view. It would be {{ name }} {{ city }} etc.
But if your view has ng-controller="CustController as cust", that means you are using "controller as" syntax, so you would need to refactor your controller code, changing $scope. to this. everywhere at least.