Error on retrieve field from database using Laravel 5 - php

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

Related

how to use DD() method in Laravel projects?

I know that for some it might be stupid or funny question (but I am newbie) but I need to find know how to properly use DD() method in laravel projects.
For example - I have got tasks to debug some code and functionality in my project (PHP laravel). And it always takes me for ever to find the exact file or folder or code where the problem is.
My mentor says to use DD() method to find things faster (but for learning purposes he didn't explain me a lot about how to actually use it and said to find out my self), but said that I should start with Route (we use backpack as well for our project). So after finding Route (custom.php file) which controller connects to my required route what should I do next? How do I implement dd() method (or as my mentor says dd('call here') method) to fast find what I should be looking for to solve my problem and complete my task? Where should I write this dd() and how should I write it?
Thank you for the answer in advance!
for example I have a:
public function create(): View
{
return view('xxxxxx. \[
//
//
\]);
}
and if I put dd() anywhere in the code, I get error message in my URL :(
first of all ,in Laravel we use dd() before return in order to read any variable.
in controller we often use two kinds of variables : collection(which we get its members via foreach) or singular variable (we get it via its name)for example:$var = 1; dd($var).
notice:
if you are using ajax response you will not be able to see dd() results in page ,you can see the result via network tab in your browser (if u inspect your page).
dd stands for "Dump and Die."
Laravel's dd() function can be defined as a helper function, which is used to dump a variable's contents to the browser and prevent the further script execution.
Example:
dd($users,$variable1,$var2);
You can use dd() in blade
#foreach($users as $user)
#dd($user)
OR
{{dd($user)}}
#endforeach
#dd($var1)
You can read this article, the have more example and comparison
https://shouts.dev/articles/laravel-dd-vs-dump-vs-vardump-vs-printr-with-example
As Laravel is following model-view-controller or MVC design pattern. First go to the route and check which controller is called in the URL with the related URL.
Then go to the controller. **dd**() function is basically a dump and die. you also can do this by **print** or **echo** function too.
Lets assume that I have a controller name ProductController where I have method name index.From where I need to show a list of products in a table.
// in controller
public function index()
{
$products = Products::all();
// here you think ,I need to check whether I am getting the output or
not.
dd( $products );
//Or echo $products;
return view ('product.list',compact('products'));
}
let's suppose you are getting everything but in view when you loop through the products you declare the wrong variable name or mistakenly do some spelling mistakes. and want to see the result.
In view just do the dd() method by the following way:
{{ dd($products) }}

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.

octobercms database query cache not working

In one of my pages I perform a database query like so..
function onStart()
{
$this['numz'] = Db::table('backend_users')->select('id')->count();
}
This works as expected and returns me a value that I can use in the page like so
There are a total of {{ numz }} ppl.
Now according to this, we should be able to do ...
function onStart()
{
$this['numz'] = Db::table('backend_users')->select('id')->remember(10)->count();
}
However when ever I try this, I get the following error;
Call to undefined method Illuminate\Database\Query\Builder::remember()
Any idea what the issue is or is this a bug?
This is a bug that has now been fixed in build 398+.
https://github.com/octobercms/october/issues/2639

Passing counter variable from controller to View in laravel 5

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.

Laravel4 - Trying to create widget like partials that will pass/accept a parameter to get the correct data

Within my views I am trying to reuse a partials, so I can create a list of latest posts anywhere in the site / sidebar by using the blade #include where the passed variable is the number of posts to be included, like this:
#include('widgets.lastestposts', array('numPosts' => '10')
However the problem I have is how to get the Post data for the correct number of posts within the partial?
I could pass through a list of all posts via Post::all() using the controller or even a View::composer and then within the partial use a #for|#endfor loop to only show the correct number based on the 'numPosts' value.
However this doesn't feel right and I am sure there must be a better way than pulling a complete list of Posts when I may only need 5 or 10.
I tried View::composers but I could find how to pass through a variable so I can get the correct number of Posts returned. I can't access the parameter 'numPosts' via
$view->getdata()
as I expect 'numPosts' needs to be passed to the view via the controller, rather than the Blade file - either that or I messed up!
Am I missing something easy here or is what I am looking to do actually a very bad idea and I should be doing something else?
Any pointers are most gratefully received. Thanks!
(ps - I was looking to be able to do this via the blade file rather than setting up the number of posts in the controller to allow our designers/HTML coders to simply add the widgets and parameters to the views rather than have to mess with controllers.)
I would do this using View Composers. You can pass data to the composer with your include:
#include('widgets.lastestposts', array('numPosts' => '10')
and then from within the view composer you should be able to access that param like so:
View::composer('widgets.latestposts', function($view)
{
$view_data= $view->getData();
$post_count = $view_data['numPosts'];
//You will have to implement something to do this
$post_data = Post::getLatestPosts($post_count);
and then you can pass the post data back with:
$view->with('posts', $post_data);
}
and then from within your blade partial widgets.latestposts you can iterate over $posts to display the posts.
I know you said in your post that you tried this method, but I am fairly certain that this approach should work. Double check all your filenames, file extensions (.blade.php) etc...
Hope this works.
Using a view composer is pretty easy:
You can, for instance, store your number of posts in a Session var:
View::composer('*', function($view)
{
$view->with('numPosts', Session::get('numPosts'));
}
Or just hardcode them:
View::composer('*', function($view)
{
$view->with('numPosts', 10);
}
And use it in your view:
<?php $i=1; ?>
#foreach($posts as $post)
{{ $post->title }}
<?php
$i++;
if ($i > $numPosts) break;
?>
#endforeach
Assuming that you've passed $posts to your view:
$posts = Post::all();
return View::make('your-view')->with('posts', $posts);
But, remember, you also can do things like
$posts = Post::orderBy('created_at', 'desc')->take(Session::get('numPosts'))->get();
// or
$posts = Post::orderBy('created_at', 'desc')->take(10)->get();
// and
return View::make('your-view')->with('posts', $posts);
So you won't have to filter them again in your view.

Categories