How to get weekly and monthly report in laravel? - laravel

I want to get weekly reports and monthly reports on my application, but I don't know where to start.
I use Laravel 5.7, I have tried a number of experiments that I have searched for on the internet, but they don't work.
My table
Schema::create('surat_keluars', function (Blueprint $table) {
$table->increments('id');
$table->string('nomor_surat')->unique();
$table->integer('instansi_id')->unsigned();
$table->string('perihal');
$table->date('tanggal_surat');
$table->date('tanggal_kirim');
$table->string('lampiran');
$table->timestamps();
$table->foreign('instansi_id')->references('id')->on('instansis');
});
My model
class SuratKeluar extends Model
{
protected $fillable = [
'nomor_surat', 'instansi_id', 'perihal', 'tanggal_surat', 'tanggal_kirim', 'lampiran'
];
public function instansi()
{
return $this->belongsTo('App\Instansi');
}
}
And and I have tried using this controller, but I don't know how to display it in view blade
public function day()
{
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m');
});
}
I hope someone can help me.

based on your question if you want to show it in view you can return the controller to the view like this:
public function day(){
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m')});;
return view('name_of_the_view')->with('name_of_variable_in_view', $data);
}
please make sure the $data variable is the data for your report by using var_dump like this
public function day(){
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m')});;
var_dump($data);
}
and please ensure that you already build the view for your review you can read the documentation in here https://laravel.com/docs/5.7/views

Related

Dynamically use of model to send relationship value in a view in laravel

I am working on a bookmarking type of websites and want to show links related to their respective category on the category page. One link can only have one category.
I have created the model and view but having problem with the code of the controller to get data dynamically.
Links table
{
Schema::create('links', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->text('link');
$table->text('title');
$table->text('description');
$table->integer('category_id');
$table->integer('votes');
$table->dateTime('submitted_at');
$table->rememberToken();
});
Categories table
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->string('status');
$table->timestamps();
});
}
Category Model
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'name', 'slug', 'status',
];
public function links()
{
return $this->hasMany('App\Links');
}
}
Links Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Links extends Model
{
//
protected $fillable = [
'user_id', 'link', 'title', 'description', 'submitted_at', 'category_id','votes',
];
public $timestamps = false;
public function category()
{
return $this->belongsTo('App\Categories');
}
}
Categories controller
public function index($slug)
{
$getcategoryid = DB::table('categories')->where('slug', '=', $slug)->get();
$catid = $getcategoryid[0]->id;
$catlinks=new \App\Category;
$catlinks=$catlinks::find(1)->Links;
return $catlinks;
The problem is I want find(1) to be dynamic according to the page. like if I can use $catid like find($catid) or something?
How can I get data to a category page if is has links then show and if not show a message no link found. like using count()
Seems like you are trying to load the links of a single category given a slug, you can do that like this:
// Do not forget to add this line after the namespace declaration
use App\Category;
public function index($slug)
{
return Category::whereSlug($slug)->firstOrFail()->links;
}
But a nicer way would be to set up route model binding for your category model.
To do so, in your Category class put this method:
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'slug';
}
Important: in your route file, make sure to replace the {slug} parameter of your route with {category} otherwise route model binding would not work at all.
Then in your controller class the index function would become:
public function index(Category $category)
{
return $category->links;
}
You can read more about route model binding in the documentation
Updated answer
If you want to customize the response when the category doesn't exists you can do like the code below (in this case without using route model binding).
// Do not forget to add this line after the namespace declaration
use App\Category;
public function index($slug)
{
$category = Category::whereSlug($slug)->first();
if (! $category) {
return response()->json([]);
}
return response()->json($category->links);
}
To get links that belong to a category with $slug you can do:
$links = Link::whereHas('category', function($query) use ($slug) {
$query->where('slug', $slug);
})->get();
You can do it with a JOIN too, but this is simpler and clearer.
Also, when you have models, you don't need to use DB::table(...), and you don't have to make a model instance manually. The instance will be created behind the scenes when you do Link::whereHas.
First of all, your code is a bit all over the place, so for example in Laravel its recommended to keep all Class names singular, but you have used Links instead of Link. 2nd your database structure could be better, for example when you use relationships the column type should match the id of the linking table, so if the id is a bigIncrements, the linking category_id field should be an unsignedBigInteger, also utilise foreign keys.
To try to help you
public function index($slug)
{
$category = \App\Category::where('slug', '=', $slug)->first();
$catlinks = $category->links;
return view('name.of.view', ['links' => $catlinks]);
}
If you learn Route Model Binding you can also do it like so
public function index(\App\Category $category)
{
$catlinks = $category->links;
return view('name.of.view', ['links' => $catlinks]);
}
Then in your view you can use the #forelse blade directive like so
#forelse($links as $link)
Do something with the link
#empty
Message to display if empty
#endforelse
But what I would really recommend is learn Laravel, the docs are extremely good. THen you can do this in your controller:-
public function index(\App\Category $category)
{
return view('name.of.view', ['category' => $category]);
}
Then in your view you can use the #forelse blade directive like so
#forelse($category->links as $link)
Do something with the link
#empty
Message to display if empty
#endforelse
Unfortunately, there is no way of getting a better knowledge and understanding of the framework than to put the time into read and use the docs
remember:
instead of \App\Category or \App\Links you can include it top of controller like this use App\Category; and use App\Links;
instead of
$getcategoryid = DB::table('categories')->where('slug', '=', $slug)->get();
$catid = $getcategoryid[0]->id;
use
$catid = Category::where('slug', '=', $slug)->first();
and instead of :
$catlinks=new \App\Category;
$catlinks=$catlinks::find(1)->Links;
return $catlinks;
use
return catlinks = $catid->links;
this code return all links belong to category
if you want to pass this data to view
use
return view('exampleview',compact('catid'));
and in view you can check catid has links or not
#if($catid->links->count() > 0)
has link
#else
no link
#endif

Laravel : get the top 10 users from answer's survey table

I want to display the top 10 users who are answering for the surveys
I tried this
public function topuser()
{
$bestuser = Answer::whereRaw('id = (select max(count(`id`)) from Answer)')->get();
return view('dashboard.top')->with('bestuser', $bestuser);
}
But it gives me an error.
Answer model:
class Answer extends Model
{
protected $fillable = ['answer'];
protected $table = 'answer';
public function survey() {
return $this->belongsTo(Survey::class);
}
public function question() {
return $this->belongsTo(Question::class);
}
}
Answer Migrate file :
public function up()
{
Schema::create('Answer', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('question_id');
$table->integer('survey_id');
$table->string('answer');
$table->timestamps();
});
}
How to fix that, please?
If you are looking for top users (those with the most posts), it would probably be easier to come from the User model angle. Thus, pull a count from the Answer relationship on the User model, something like this:
$bestuser = User::withCount('answers as answer_count')
->orderBy('answer_count', 'desc')
->take(10)
->get();
Or if you just want a simple list:
$bestuser = User::withCount('answers as answer_count')
->orderBy('answer_count', 'desc')
->take(10)
->pluck('answer_count', 'name');
you can do like this
public function topuser()
{
$bestuser = Answer::OrderBy('created_at', 'DESC')->take(10)->get();
return view('dashboard.top')->with('bestuser', $bestuser);
}

Laravel how to get id parameter in model relation?

I've got a query to get messages:
public function getMessagesFor($id)
{
$messages = Message::where(function($q) use ($id) {
$q->where('from', auth()->id());
$q->where('to', $id);
})->orWhere(function($q) use ($id) {
$q->where('from', $id);
$q->where('to', auth()->id());
})->get();
}
and this logic works as it should, no errors all is ok. Now I want to get messages directly via model relatioship with other user (not authenticated one)
so in User model I wrote:
public function messages()
{
return $this->hasMany(Message::class, 'to', 'id')
->where('messages.from', auth()->id());
}
And this basically gives the same result as first where clause in getMessages function. This relatioship works ok.
The problem is that I don't know how to code the second part of where clause. I don't have access to $id in my model so how should I approach to this? Any ideas how to code it?
edit: message migration:
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->integer('from')->unsigned();
$table->integer('to')->unsigned();
$table->boolean('read')->default(false);
$table->integer('offer_id')->nullable();
$table->mediumText('body')->nullable();
$table->timestamps();
});
So I think the problem is the model relationship (user) is already set to get message where the user is the message reciever(to),
$this->hasMany(Message::class, 'to', 'id')
so you need to define another relationship to get messages where the user is the sender (from), so you have this
//user is reciever
public function sentMessages() {
return $this->hasMany(Message::class, 'to', 'id')
->where('messages.from', auth()->id()); }
//user is sender
public function recievedMessages() {
return $this->hasMany(Message::class, 'from', 'id')
->where('messages.to', auth()->id()); }
Anyway I advise you go with your first approach.
Okay, so adding your final soultion to get messages
//get all messages with
$this->sentMessages->merge($this->recievedMessages)

How can i create dynamic delete method in laravel?

in codeigniter i can set method for dynamic delete like this code.in laravel how can i set this method for dynamic delete method.Thanks
in controller function
public function Delete($id)
{
if ($this->process_model->DynamicDelete($id, "interest_statement")) {
//
}
}
in model function
public function DynamicDelete($id, $table)
{
$this->db->delete($table, ['id' => $id]);
return TRUE;
}
you can use route as like below:
Route::get('yourroute/{info}','Yourcontrolller#Yourmethod');
and use this route in view page where from request get:
{{ URL::to('/yourroute/'.$id.'&your_table')}}
and finally you write a function in your controller
public function Yourmethod($info){
$explode=explode('&',$info);
DB::table($explode[1])->where('id',$explode[0])->delete();
Session::flash('flash_message', 'Your Data Delete Successfully');
return back();
}
Thank you
In Laravel, you can use Raw Query (Database: Query Builder)
Example:
Table: users
Condition: votes > 100
DB::table('users')->where('votes', '>', 100)->delete();
In your case:
public function DynamicDelete($id, $table) {
return DB::table($table)->where('id', '=', $id)->delete();
}

How to get posts of people I am following in Eloquent

I have a User model, a Post model.
In my User model, I have the following:
public function followers()
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')->withTimestamps();
}
public function following()
{
return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')->withTimestamps();
}
public function posts()
{
return $this->hasMany(Post::class);
}
So basically, $user->following gives me a collection of users I am following and $user->posts gives me the collection of posts. I want to do this:
$posts = [];
$user->following->each(function($f) use($posts) {
$posts[] = $f->posts;
});
but more Eloquenty way, if that makes sense. Because I want to paginate the result after this. I was thinking of doing hasManyThrough, but cannot figure out how?
Here is link to similar question with an answer.
I think you wan tot do something like this:
User::where('id', $id)->with(['following.posts' => function ($q) use (&$posts) {
$posts= $q->get()->unique();
}])->first();

Resources