next/prev month is not working in laravel - php

So I have this view that shows a table and two buttons (next/prev). Each button has a query string /?date=next that I capture in my controller using request()->has('date').
<a class="button is-primary is-outlined" href="/?date=prev">Previous</a>
<a class="button is-primary is-outlined" href="/?date=next">Next</a>
The user shall be able to go to next month, and the month after that depending on how many times he clicks on the next/prev button.
Initially, I had two approaches. First, I thought to myself that I can use a $count that increments whenever the user clicks the button in $post->whereMonth('date', $this->count). Second, simply use the Carbon library, $post->date->addMonth().
In both approaches, the date remain the same despite the number of times the next/prev button was clicked.
First approach:
class PostsController extends Controller
{
protected $count;
public function __constructor(){
$this->count = 0;
}
public function show(Hour $post){
if(request()->has('date') == 'next'){
$posts = $post->whereMonth('date', $this->count);
$this->count++;
} else if(request()->has('date') == 'prev'){
$posts = $post->whereMonth('date', $this->count);
$this->count++;
}
return view('user.table', compact('posts'));
}
}
Second approach (favorite):
public function show(Hour $post){
if(request()->has('date') == 'next'){
$posts = $post->date->addMonth();
} else if(request()->has('date') == 'prev'){
$posts = $post->date->subMonth();
}
return view('user.table', compact('posts'));
}
I've seen that Laravel provide the query builder increment, but that only work for columns, and not variables.
Is there a way I can make this work by remembering the previous date as shown in the second approach.

Looks like you just want to display a date. In this case, do this:
public function show(Hour $post)
{
$months = request('months', 0);
if (request('date') === 'next'){
$posts = $post->date->addMonth();
$months++;
} elseif(request('date') === 'prev'){
$posts = $post->date->subMonth();
$months--;
}
return view('user.table', compact('posts', 'months'));
}
And in the view:
<a class="button is-primary is-outlined" href="/?date=next&months={{ $months }}">Previous</a>
<a class="button is-primary is-outlined" href="/?date=next&months={{ $months }}">Next</a>

Related

How can I output the Cart item number?

i was wondering of how can i show how many items i got in the cart? I did a path in the twig but im not sure how to show it.
this is my controller i have the route and in the twig i call the path with the name (count_panier).
/**
* #Route("/count/{qtt}", name="count_panier")
*/
public function testAction($qtt,Request $req)
{
$qtt = $this->afficherCount($req);
return $this->redirectToRoute('mag',['count'=>$qtt]);
}
//----------------------------------------------
public function afficherCount(Request $req){
$sess = $req->getSession();
$panier = $sess->get('panier',[]);
$qtt = 0;
foreach($panier as $item)
{
$qtt += $item->quantiteCommandee;
}
return $qtt;
}
And this is my twig, this is the part of the top navbar
<div class="menu">
<a class="active" href="{{path('mag')}}">Catalogue</a>
Contact
Crée un compte
Connexion
<a href="panier">Panier
<img width="30" alt="img" src="{{asset('images/cart.png')}}"/></a>
<span id='panierCompteur'>
items</span>
</div>
in your Controller you are passing just one parametere count => '$qtt
So in the Twig file, if you want get it, do this:
{{ count }}
So if you want to get a link that shows how many items you have, do like this:
<span id='panierCompteur'>
{{count}}
items</span>
(you are not usign the $qtt variable so don't pass it)
/**
* #Route("/count", name="count_panier")
*/
public function testAction(Request $req)
{
$qtt = $this->afficherCount($req);
return $this->redirectToRoute('mag',['count'=>$qtt]);
}
//----------------------------------------------
private function afficherCount(Request $req){
$sess = $req->getSession();
$panier = $sess->get('panier',[]);
$qtt = 0;
foreach($panier as $item)
{
$qtt += $item->quantiteCommandee;
}
return $qtt;
}
Of course the first time you render this main page you need to run the function afficherCount() in the index Controller (or whatever is your main controller) and return to the main page the count => '$qtt with all your others arguments.
You are redirecting to another route, so you need to "handle" the redirection if you want to get those parameters:
/**
* #Route("/your-route/{count?}", name="mag", requirements={"count"="\d+"})
*/
public function yourFunction(Request $req, $count)
{
// true if is the first time you render this page or if you don't pass the value
if($count === null){
$count = afficherCount($req);
}
return $this->Render('yourTwigFile.html.twig',['count'=>$count]);
}
{count?} : the ? if for optional parameters so the first time you render this page is not necessary to pass the value in the URL
requirements={"count"="\d+"} : the value can only be an integer
(PS. this function is probably your index)
for more information / examples

Laravel return UserTitle By Count

On my project I'm tying to generate user titles by users' post, comments, questions and answers count from titles table.
I have titles table which can I add new titles. And each title has own post count. So when a user has greater or equal post count title will be generated from titles table.
Problem is I can't fetch the greater value in the titles table with users post count. When I use <= it shows the title but when I use >= it doesn't return anything.
Ps: There aren't any relation between users and titles table. It returns only equal title data.
My codes are below:
public function title()
{
$commentcount = $this->hasMany('App\Comment')
->whereUserId($this- >id)
->count();
$questioncount = $this->hasMany('App\Question')
->whereUserId($this->id)
->count();
$answercount = $this->hasMany('App\Answer')
->whereUserId($this->id)
->count();
$total = $commentcount + $questioncount + $answercount;
$title = Title::where('postcount', '>=', $total)->first();
if ($title) {
$show = '<span class="badge badge-danger rutbe" style="background:' . $title->color . '">' . $title->text . '</span>';
return $show;
} else {
return false;
}
}
I can't figure out why doesn't return anything when greater or equal count.
I'll sum up my answer based on my comment and give the hints with regards to your queries.
Basically the where conditition in your codes matches multiple title entries. Therefore selecting the first will not always match the correct one. As you want to match the "lowest" matching title you probably want to change
$title = Title::where('postcount', '>=', $total)->first();
to
$title = Title::where('postcount', '>=', $total)->orderBy('postCount', 'ASC')->first();
Some other enhancement proposals
$commentcount = $this->hasMany('App\Comment')
->whereUserId($this- >id)
->count();
Seems to be weird to use in your (probably User?) class. You should refactor this to something like
public function comments()
{
return $this->hasMany('App\Comment');
}
This defines your users realtion to his comments. If you now want to have the amount of the users comments in your title function you can simply do
$this->comments()->count();
When doing this for all 3 of your relations your title method could look like
public function comments()
{
return $this->hasMany('App\Comment');
}
public function questions()
{
return $this->hasMany('App\Question');
}
public function answers()
{
return $this->hasMany('App\Answer');
}
public function title()
{
$total = $this->comments()->count() + $this->questions()->count() + $this->answers()->count();
$title = Title::where('postcount', '>=', $total)->orderBy('postcount', 'ASC')->first();
if ($title)
return '<span class="badge badge-danger rutbe" style="background:' . $title->color . '">' . $title->text . '</span>';
}
return false;
}
This does not only make it look & feel way cleaner - it also helps you with future queries where you handle these relations.

Use of different Method from Controller on Button in HTML

crew,
I have a controller_jobs.php in which I have two methods. The index method in which every job from my database that is available is pulled from the DB and assigned to my template, career.html. In the career.html I display every available job through a foreach, this works as intended.
The second method is called show and is called with the primary key from the job.
In my html I got a Button at every job position. The HTML was designed from another company and is still hardcoded with an href call to the second template career-details.html.
How can I manage to call the show() function from the controller on this button and start the next template??
<div class="wu__ltblue--bg eq row--flex row--aic row--jcc">
<a href="career-details.html" class="btn btn-borderd">
<span class="fa-stack">
<i class="fa fa-circle fa-stack-2x icon-background1"></i>
<i class="fa fa-chevron-right fa-stack-1x"></i>
</span> Ansehen</a>
</div>
I was told to use a form to call the method in there, but I'm not certain about how to use it.
Thanks for help in advance.
The example I got was to lookup on things they already did.
<form id="form_reserve" method="post" action="{$SITEURL}payprocess&PHPSESSID={$SID}"> "Buttoncode" </form>
To be honest, i don't understand what they did in there as I am pretty new to webdevelopment.
And these are my functions from the controller.php
public function index() {
$js_array = array();
$jobs = array();
$dbJobs = new DBJobs();
$jobs = $dbJobs->getAll();
$ControllerLibs = new ControllerLibs();
foreach ($jobs as &$job) {
$job['STELLENKURZBESCHREIBUNG'] = $job['STELLENKURZBESCHREIBUNG'];
$job['STELLENBESCHREIBUNG'] = $job['STELLENBESCHREIBUNG'];
$job['PDFDOKUMENT'] = $job['PDFDOKUMENT'];
$job['BILD'] = $job['BILD'];
$job['PK'] = $job['PK'];
$template = $this->template;
$template->assign('JS_FILES', $js_array);
$template->assign('JOBS', $jobs);
$template->display('career.html');
} // Index
public function show($pk) {
$js_array = array();
$jobs = array();
$dbJobs = new DBJobs();
$jobs = $dbJobs->getByPK($pk);
foreach ($jobs as &$job) {
$job['STELLENKURZBESCHREIBUNG'] = $job['STELLENKURZBESCHREIBUNG'];
$job['STELLENBESCHREIBUNG'] = $job['STELLENBESCHREIBUNG'];
$job['PDFDOKUMENT'] = $job['PDFDOKUMENT'];
$job['BILD'] = $job['BILD'];
}
}

Laravel detect if there is a new item in an array

I want to implement a system in my project that "alerts" users when there is a new comment on one of their posts.
I currently query all comments on the posts from the logged in user and put everything in an array and send it to my view.
Now my goal is to make an alert icon or something when there is a new item in this array. It doesn't have to be live with ajax just on page load is already good :)
So I've made a function in my UsersController where I get the comments here's my code
public function getProfileNotifications()
{
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
if (!empty($comments_collection)) {
$comments = array_collapse($comments_collection);
foreach($comments as $com)
{
if ($com->from_user != Auth::user()->id) {
$ofdate = $com->created_at;
$commentdate = date("d M", strtotime($ofdate));
$comarr[] = array(
'date' => $ofdate,
$commentdate,User::find($com->from_user)->name,
User::find($com->from_user)->email,
Project::find($com->on_projects)->title,
$com->on_projects,
$com->body,
Project::find($com->on_projects)->file_name,
User::find($com->from_user)->file_name
);
}
}
} else {
$comarr = "";
}
}
Is there a way I can check on page load if there are new items in the array? Like keep a count and then do a new count and subtract the previous count from the new one?
Is this even a good way to apprach this?
Many thanks in advance! Any help is appreciated.
EDIT
so I added a field unread to my table and I try to count the number of unreads in my comments array like this:
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
$unreads = $comments_collection->where('unread', 1);
dd($unreads->count());
But i get this error:
Call to a member function where() on array
Anyone any idea how I can fix this?
The "standard" way of doing this is to track whether the comment owner has "read" the comment. You can do that fairly easily by adding a "unread" (or something equivalent) flag.
When you build your models, you should define all their relationships so that stuff like this becomes relatively easy.
If you do not have relationships, you need to define something like the following:
In User
public function projects()
{
return $this->hasMany('App\Models\Project');
}
In Project
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
Once you hav ethose relationshipt, you can do the following. Add filtering as you see fit.
$count = $user->projects()
->comments()
->where('unread', true)
->count();
This is then the number you display to the user. When they perform an action you think means they've acknowledged the comment, you dispatch an asynchronous request to mark the comment as read. A REST-ish way to do this might look something like the following:
Javascript, using JQuery:
jQuery.ajax( '/users/{userId}/projects/{projectId}/comments/{commentId}', {
method: 'patch'
dataType: 'json',
data: {
'unread': false
}
})
PHP, in patch method:
$comment = Comment::find($commentId);
$comment->update($patchData);
Keep in mind you can use Laravel's RESTful Resource Controllers to provide this behavior.
try this
$unreads = $project->comments()->where('unread', 1);
dd($unreads->count());
EDIT
My be Has Many Through relation will fit your needs
User.php
public function comments()
{
return $this->hasManyTrough('App\Project', 'App\Comment');
}
Project.php
public function comments()
{
return $this->hasMany('App\Comment');
}
then you can access comments from user directly
$user->comments()->where('unread', 1)->count();
or I recommend you define hasUnreadComments method in User
public function hasUnreadComments()
{
$return (bool) $this->comments()->where('unread', 1)->count();
}
P.S.
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
this code is horrible, this way much better
$projects = Auth::user()->projects;

how to get the data from array when multiple model functions pass to the view from the controller

I have a controller it take multiple model function results and pass it to controller I did it like this
adpreview_ctrl.php
public function showBusinessReviews($vehicleid){
$data=array();
$data['details']=$this->ads_model->getBusinessReviews($vehicleid);
$data['noOfReviews']=$this->ads_model->countReviews($vehicleid);
$this->load->view('pages/templates/header');
$this->load->view('pages/viewReviews',$data);
$this->load->view('pages/templates/footer');
}
public function countBusinessReviews($vehicleid){
$data['details']=$this->ads_model->countReviews($vehicleid);
$this->load->view('pages/templates/header');
$this->load->view('pages/viewReviews',$data);
$this->load->view('pages/templates/footer');
}
}
viewReviews.php
<?php
foreach($noOfReviews as $reviewAmount){
echo $reviewAmount.'Reviews';
}
foreach($details as $review){
$Breview=$review->rating;
if($details==null)
{?>
<?php echo '<center><b><h3>No any reviews has been posted yet!</h3></b></center>';?>
<input type="submit" name="ok" class="btn btn-primary btn-lg" value="ok">
<?php }
else{
?>
Ads_model.php
public function getBusinessReviews($Vehicleid){
$status="Approved";
$this->db->select("*");
$query=$this->db->where('Vehicleid',$Vehicleid);
$query=$this->db->where('Status',$status);
$query=$this->db->get('businessreviews');
return $query->result();
}
public function countReviews($Vehicleid){
$status="Approved";
$this->db->select("*");
$query=$this->db->where('Vehicleid',$Vehicleid);
$query=$this->db->where('Status',$status);
$query=$this->db->get('businessreviews');
return $query->num_rows();
}
what I need to know is, it gives error saying it cannot identify $noOfReviews.
foreach($noOfReviews as $reviewAmount){
echo $reviewAmount.'Reviews';
}
I need to know how to retrieve multiple model function data in view,
and $noOfReviews only gives the no of reviews, a user has given. So their, without using a foreach loop how can i get the value of that, using a foreach loop is not necessary here.
Try this:
model:
public function countReviews($Vehicleid) {
$status = "Approved";
$this->db->select("*");
$query = $this->db->where('Vehicleid', $Vehicleid);
$query = $this->db->where('Status', $status);
// it will return with only the number of data
return $query->count_all_results('businessreviews');
}
viewReviews.php
<?php
// show number of reviews
echo $noOfReviews . 'Reviews';
// show details if exists
if(!empty($details)) {
foreach($details as $review) {
// echo what you want
}
} else {
echo 'No details.';
}
?>

Categories