count visitor of pages in laravel - php

How can i count visitor of pages in Laravel, prefer to use cache
public function IndexShow(){
Cache::put('home',0);
$counter = Cache::increment('home',1);
}

Check out this package then if google analytics is not an option for you. - https://github.com/antonioribeiro/tracker
They have thought through some things you would be seeking to do. You will end up with something like below.
//in your controller
$weeklyUsers = Tracker::users(60 * 24 * 7);
//in your blade
<div>
<span class="h4 d-block font-weight-normal mb-2">{{ $weeklyUsers }}</span>
<span class="font-weight-light"><strong>TOTAL VISITOR</strong></span>
</div>

Related

How to display multiple datasets by month in highchart?

I have a database called sales which I'm trying to display in my chart like this but can't.
id
products
earnings
created_at
1
Jasmine
50
2023-01-14 18:55:34
2
How to cook
150
2023-01-14 18:55:34
3
Jasmine
100
2023-01-14 18:55:34
4
Dictionary
200
2023-01-14 18:55:34
5
How to cook
70
2023-02-20 17:23:54
It is my first time trying to do it in chart and tried other codes from tutorials
and ended up with this result
I'm trying to display it like the first chart, but instead by month with multiple datasets where the month will contain the name of the products and its earning on that month. like this
Pardon my unsightly editing
This is the working code that I managed to follow and do, but don't know how to modify it to obtain the desired output. I tried but gets an error, so I put it back.
$now = Carbon::now();
$yr = $now->format('Y/m/d');
//monthly
{
$m= $now->format('m');
$date_start = Carbon::create(date('Y'), "1");//january start
$data=[];
$monthdata=[];
$x=0;
for ($month = $m; $x <= 7; $month++)
{
$x=$x+1;
$date = Carbon::create(date('Y'), $month);
$date_end = $date->copy()->endOfMonth();
$saledate = DB::table('sales')
->select(DB::raw('sum(earnings) as sale'))
->where('created_at', '>=', $date)
->where('created_at', '<=', $date_end)
->get();
$sum=0;
foreach ($saledate as $row)
{
$sum=$row->sale;
}
array_push($data,$sum);
array_push($monthdata,$date->format('M'));
}
$saleChart1= new UserChart;
$saleChart1->labels($monthdata);
$saleChart1->dataset('Sales', 'bar',$data )->options([
'color' => '#2596be',
]);
}
Inside my blade file,
<div class="col-lg-6 mb-5">
<div class="card card card-raised h-100 ">
<div class="card-header text-dark bg-success px-4" style="background-color:#198754 !important">
<i class="fas fa-chart-area me-1 text-white"></i>
Monthly Sales
</div>
<div class="card-body bg-white">
<div class="col-lg-12 " >
<div id="myAreaChart1" class="mt-4" style="height: 300px;">
{!! $saleChart1->container() !!}
<script src=https://cdnjs.cloudflare.com/ajax/libs/echarts/4.0.2/echarts-en.min.js charset=utf-8></script>
{!! $saleChart1->script() !!}
</div>
</div>
</div>
</div>
</div>
My UserChart class,
<?php
namespace App\Charts;
use ConsoleTVs\Charts\Classes\Chartjs\Chart;
class UserChart extends Chart
{
/**
* Initializes the chart.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
}
Please help, can't find other tutorials, all I found now are pie charts and line graphs and doesn't display similar to what I'm looking for. What should I do to achieve the desired output?
It doesn't seem like ConsoleTVs\Charts\Classes\Chartjs\Chart has that capability. However, you might be able to get ConsoleTVs\Charts\Classes\Echarts\Chart to work closer to what you'd need.
If I were you I'd change your UserChart class to
<?php
namespace App\Charts;
use ConsoleTVs\Charts\Classes\Echart\Chart;
class UserChart extends Chart
{
/**
* Initializes the chart.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
}
Then using example from https://echarts.apache.org/examples/en/editor.html?c=bar-label-rotation
you should be able to mold your data into the correct format.
It seems as though most of the setup is pushed into an option array. Some of which you can see on the class itself https://github.com/ConsoleTVs/Charts/blob/main/src/Classes/Echarts/Chart.php
You should be able to set the options with $saleChart1->options([//...]);
Happy coding :-)

Laravel component is not receiving variables, no matter what i do

First, i have the component file, located at resources/views/component.
game-card.blade.php
#props(['game'])
<div class = 'games'>
<a href = 'game/{{$game->id}}'> view page </a>
<p> game: {{$game->name}} </p> <br>
<p> genre: {{$game->genre}} </p> <br>
</div>
Then this component is called at my view, located in resources/views
listing.blade.php
#extends('layout')
#section('list')
<div class = 'listContainer'>
#unless(count($games) === 0)
#foreach($games as $game)
//doesn't work
<x-game-card :game = "$game"/>
#endforeach
#else
<p> 0 Games </p>
#endunless
</div>
#endsection
The variable $game is not passed in the component <x-game-card/>, i even tried to use short atribute syntax (<x-game-card :$game/>) but it still doesn't work.
If it matters, the file listing.blade.php is yielded at the file layout.blade.php, located in the same folder.
layout.blade.php
<body>
<!-- Header -->
#yield('list')
#yield('singlegame')
#include('partials._footer')
For any prop that you want to pass to your component, you need to register it on the component class. In this case, the class is probably app/View/Components/GameCard.php
On the class, you need to do something like:
class GameCard extends Component
{
public $game;
public function __construct($game)
{
$this->game = $game;
}
Source: https://laravel.com/docs/9.x/blade#passing-data-to-components
i found the root of the problem. I just can't believe that the solution is so simple. I am going to post it here so less people make the same mistake i did
First, create the class (i personally use the command php artisan make:component to do that) and update it just like Nico did.
Second, when you put the <x-component in the HTML, MAKE SURE TO NOT LEAVE ANY SPACES IN THE VARIABLE!!!
my mistake was using <x-game-card :game = "$game"/>
instead of <x-game-card :game="$game"/>

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();

laravel pagination returns different page

I am working on a laravel project, where I get data from an API then I want to display it on pages. I want the return to be spread out across 4 pages, each page with 10 results each. What I have so far, seems like it should work, but I am missing one piece, so any advice and help would be appreciated. So this is how it is suppose to work with code:
1) The users types in a book title in a search box.
<form method=POST action='/search'>
#csrf
<input type="text" name="search_term"/>
<input type="submit" value="Search"/>
</form>
2) there input is then sent to my controller, which queries the google books api.
class search extends Controller {
public function search(){
$current_page = LengthAwarePaginator::resolveCurrentPage();
echo $current_page;
$term = request('search_term');
$term = str_replace(' ', '_', $term);
$client = new \Google_Client();
$service = new \Google_Service_Books($client);
$params = array('maxResults'=>40);
$results = $service->volumes->listVolumes($term,$params);
$book_collection = collect($results);
$current_book_page = $book_collection->slice(($current_page-1)*10,10)->all();
$books_to_show = new LengthAwarePaginator($current_book_page,count($book_collection),10,$current_page);
return view('library.search')->with(compact('books_to_show'));
}
}
3) the results are then displayed on my blade
#extends('home')
#section('content')
#foreach($books_to_show as $entries)
<div class="row">
<div class="col-sm-auto">
<img class="w-50 img-thumbnail" src={{$entries['volumeInfo']['imageLinks']['smallThumbnail']}}/>
</div>
<div class="col-sm">
{{$entries['volumeInfo']['title']}}<br/>
#if($entries['volumeInfo']['authors']!=null)
by:
#foreach($entries['volumeInfo']['authors'] as $authors)
{{$authors}}
#endforeach
#endif
</div>
</div>
#endforeach
{{$books_to_show->links()}}
#endsection
This all works fine and as expected. I get 10 results on the view, and then I have a bar at the bottom which give shows me 4 different pages to choose from.
When I first type in a search term such as "William Shakespeare" My page url is:
localhost:8000/search
But, when I click on any of the pages my url becomes:
http://localhost:8000/?page=2
I understand that the ?page=* is how the pagination determines which page you are viewing, and that should be sent back to the controller. But, I am missing something on sending it back to the controller I think.
Still kind of fresh to this, so any advice is more then greatly appreciated.
LengthAwarePaginator accepts a 5th parameter in its constructor: an array of options.
the path option
$books_to_show = new LengthAwarePaginator($current_book_page, count($book_collection), 10, $current_page, [
// This will fix the path of the pagination links
'path' => LengthAwarePaginator::resolveCurrentPath()
]);
By the way, on a totally different matter, Laravel makes your life easier by slicing the collection for you, check it out:
$current_book_page = $book_collection->forPage($current_page, 10);
Hope it helps :)

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