Passing counter variable from controller to View in laravel 5 - php

I am trying to make a counter in my laravel site. This counter takes all the comments from model Comments which were created from Carbon::now() until startofMonth(). So I have my controller and function counter as so:
class CommentsController extends Controller
{
public function counter()
{
$new_comments=Comments::where('created_at', Carbon::now()->startofMonth())->get();
$counted->count($new_comments['created_at']);
return View::make('pages.dashboard')->with('new_comments', $counted);
}
}
My blade template:
<div class="row">
<div class="col-xs-3">
<i class="fa fa-comments fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">{{!!$new_comments!!}}</div>
<div>New Comments!</div>
</div>
I keep getting a variable undefined error message even though the variable is called in the controller! The dashboard page works fine when the variable is not called in the blade template.
EDIT:
I have managed to get this working if ignore the controller and add the following into my view:
{{App\Comments::count()}}
This only shows the total amount of rows in the table Comments, but I will try and add the mySQL query in to it.
I still don't know why it can't be called as a variable from the controller.

In your blade template, you are calling it correctly but ! brings such issues {{!!$new_comments!!}} it will say variable undefined.
Try it without !!, It worked for me.

First: you want to take all comments are created from begin of month to now, you need a whereBetween query, not equal.
Second: You call a undefined variable $counted. I think you need remove
$counted->count($new_comments['created_at']);
and pass $new_comments to view instead of $counted
return View::make('pages.dashboard')->with('new_comments', $new_comments);
and display comments count in view
{{ $new_comments->count() }}
Hope this help you

This is a bit of a late answer, but I believe you're passing your variables incorrectly with the ->with() function. From my experience with Laravel, ->with() uses an array syntax for passing multiple variables to a view. For example:
return View::make('pages.dashboard')
->with(["new_comments" => $new_comments, "counted" => $counted]);
// Note the array usage, works with [] or array()
Then, in your dashboard.blade.php you can call either {{ $new_comments }} or {!! $new_comments !!} to echo out that value (one ignores HTML markup, one includes it.)
On a side note, trying to echo out the contents of an Eloquent collection (i.e. Comment::get() as opposed to something like Comment::first()) may not work. You should loop over the results and echo accordingly:
#foreach($new_comments AS $new_comment)
{!! $new_comment->created_at !!}
...
#endforeach

This was solved. I was calling the return view::make(dashboard) in another (page)controller. This controller took precedent therefore this view did not occur. Therefore in my pagecontroller I applied the following:
public function dashboard()
{
$count = Comments::where('created_at', '>', Carbon::today())->count();
return View::make('pages.dashboard')->with('new_comments_count', $count);
}
I can then call new_comments_count in my view.
Many thanks for the help.

Related

Laravel use # function inside another # function in View

i want to use a function (#lang) inside another function (#sortablelink).
#lang: changed localisation depending on previous user input
#sortablelink: kysliks sortable columns (https://github.com/Kyslik/column-sortable)
Like this:
#foreach($COLUMNS_TASK as $column => $val)
<div class="th">
<p class="justify-content-center text-center">#sortablelink($val, #lang('lang.'.$val))</p>
</div>
#endforeach
When i run this code, i am getting this error: Error Call to undefined function lang()
But when i write it like this:
#foreach($COLUMNS_TASK as $column => $val)
<div class="th">
<p class="justify-content-center text-center">#sortablelink($val)#lang('lang.'.$val)</p>
</div>
#endforeach
It's working, but it only displays the results of the functions side by side, and it looks like this:
Is it possible to use a function inside another function like this? Or is there another solution here i am not seeing?
Thanks in advance and have a great day.
You can call the translator to get the value you want and if you want to pass it as the second parameter to that #sortablelink directive you can:
#sortablelink($val, __($val))
// some ways to call the translator to get a translation
__($val)
trans($val)
Lang::get($val)
app('translator')->get($val)
The #lang directive would be calling the translator and echoing the result.
Laravel 7.x Docs - Localization - Retrieving Translation Strings __ #lang
Laravel 7.x Docs - Facades - Facade Class Reference Lang

Is there a better way to pass the variables inside nested for loop from the controller to the view?

I have a running code below using Laravel 7 (latest version) and PHP 7.4.4 (latest version) but I want to ask if there is a better way to implement.
So basically, the problem lies inside the nested for loop. I want to control the variables 'semesters' and 'subjects' in the controller and pass them to the view (index.blade.php). However, 'subjects' is dependent to the 'semesters', thus, I was forcibly written down the logic inside the blade template such as:
$subjects = $semester->subjects()->where(SOME QUERY HERE)->get()
See below for the code snippet:
index.blade.php
#foreach($semesters as $semester)
#if($subjects = $semester->subjects()->where(SOME QUERY HERE)->get())
#if($subjects->isNotEmpty())
//SOME CODE HERE
#foreach($subjects as $subject)
//SOME CODE HERE
#endforeach
#endif
#endif
#foreach
Is there a best way to implement this one?
Thanks in advance.
Edit
I am also worried about the query since it is inside the loop. However, I'll just change my design specs to limit the number of 'semesters' to be shown in the view. This is also to limit the query inside the loop. But, if you have a better implementation, please suggest. Thank you very much.
I think what you want is eager load some particular subjects with their respective semester.
$semesters = Semester::with([
'subjects' => function ($query) {
$query->where() // SOME QUERY HERE.
},
])
->get();
Now when you call $semester->subjects it returns only those filtered subjects.
Example Code
#foreach($semesters as $semester)
#if($semester->subjects->isNotEmpty())
//SOME CODE HERE
#foreach($semester->subjects as $subject)
//SOME CODE HERE
#endforeach
#endif
#foreach
Edit
Now you don't have to worry about querying in a loop. As you see we have already done loading. Which is called eager loading

How do I display the value of count() inside blade view in Laravel 5.4?

I feel like I will be kicking myself for asking this question but I just can't seem to figure it out. What I'm trying to do is count the value of a collection right inside a blade view and display the result at the same time. Here's the simple code I have written
Controller
$pendingMembers = Member::where('status', '=', null)->get();
I can see the data when I die and dump $pendingMembers.
Blade view
<div class="mr-5">
{{ $pendingMembers->count() }} Pending
</div>
And that returns Undefined variable: pendingMembers so how can I achieve my desired goal?
Share your variable in your controller method to your view file.
return view('your-blade-file', compact('pendingMembers'));
More details are available on https://laravel.com/docs/5.5/views#passing-data-to-views.

Laravel: call static function inside blade template

I found very strange situation. I have a collection with some results and I wanna grab for each of that results the saved in cache information. For that I have a Cache class, which has one static function get(). Unfortunately I am not receiving anything when I call it in the foreach loop of my Blade template.
#foreach($prognoses as $sport_prognose)
<?php
$pr = Cache::get(Config::get('variables.cache.prediction'), ['id' => $sport_prognose['id']]);
print_r($pr);
die();
?>
#endforeach
If I call the same function inside the Controller is display me the needed information, but not as in the example above.
Why is that ?
You can use cache() and config() and other global helpers instead of facades to avoid this kind of problem.
Inside the blade template, you can write something like this:
{{ $pc::getProducts($ship->products) }}
Notice the use of variables. Obviously getProducts is a static method inside the controller, and $ship->products is a variable coming from an array. Let's make it simple: suppose $ship->products is 1, and getProducts is this:
static function getProducts($id) { echo "id is $id; }
If you ran this script, you'd get an error because the template lacks the value of $pc. How do you get around this? You need to pass the value of $this to the template:
return View::make('shipping.index')->with(['pc' => $this, 'shipping' => $shippings);
Here shipping.index is the template, and pc is getting a value of $this, which allows $pc to get accceess to getProducts inside the blade template.

Error on retrieve field from database using Laravel 5

Have a controller function:
public function pageedit($id)
{
$page = Pages::where('pgeID','=',121)->get();
return view('admin.pageedit')->with('page',$page);
}
And a simple view:
#extends('admin')
#section('content')
#include('/partials/adminpageheader')
Edit Page {{ $page }}
#endsection
When I run this, I get the output as follows:
Intranet Web Control Panel (Pages)
Admin Home - Admin Home Page
Edit Page
[{"pgeID":"121","pgeActive":"0","pgeContent":"1","pgeMainLevel":"6","pgeLevel":"1","pgeParent":"6","pgeOrder":"3","pgeTitle":"Employee Assistance Program","pgeHeader":"Null","pgeBody":Employee Assistance Program that all employees can access 24\/7. The website, www.assist.com has an amazing amount of information available. If you are looking for training, articles, resources and more, check them out. The use","pgeNav":null,"pgeContents":"Null","pgeCallOut":"Null","pgeEditor":"Null","pgeTitleDRAFT":"Null","pgeTemplateDRAFT":null,"pgeNavDRAFT":null,"pgeContentsDRAFT":"Null","pgeCallOutDRAFT":"Null"}]
So I know it is pulling the data correctly. But when I try to display JUST the page title (pgeTitle) I get an undefined property error if I try {{ $page->pgeTitle }} and an undefined index error if I try {{ $page['pgeTitle'] }}
I know it has to be something simple I am forgetting, but I will be danged if I can figure out what it is. Thoughts?
Instead of using ->get() use ->first(). This will return a single instance as opposed to the collection, which is the difference between having to use an array accessor and not.
$page = Pages::where('pgeID','=',121)->first();
^
first==single
get==array collection
$page is an array, where the index is numeric as far as i can tell, so you should do:
{{$page[0]->pgeTitle}}
The same answer than Taxicala, but I'd suggest you to use ->first() method instead of get, since you're looking for only 1 row.
$page = Pages::where('pgeID','=',121)->first();

Categories