Laravel: Why isn't the query result showing in my view? - laravel-5

I am successfully getting results in/from my controller like this:
$session_id and $user_id are getting passed into my method.
Controller
// get all sets belonging to the user for the given session
$session = Session::findOrFail($session_id);
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id);
$user = User::findOrFail($user_id);
return View('users.index')
->with('session', $session)
->with('sets', $sets)
->with('user', $user);
View
<p>{{ $user->first_name }} has {{ $sets->count() }} existing set{{ ($sets->count() > 1 ? 's': '') }}.</p>
<ul class="list-unstyled">
#foreach ($sets as $set)
<li>
Set
</li>
#endforeach
</ul>
I am seeing "Foo has 1 existing set." and I can see the record in the DB. However, I'm not getting into the loop at all. If I add/remove records, my paragraph text updates accordingly as well - but I still never get into the loop to show each set. I'm sure it's something obvious, but I sure don't see it.
Thank you for any suggestions!

Change the query of sets to this:
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id)->get();
As get() method will return you the collection object.

Related

i am trying to show single data but it is showing" Trying to get property 'id' of non-object"

**after clicking "read more" i want to show a single post**
<a href="{{ URL::to('single/blog/'.$post->id) }}" class="btn btn-primary
float-right">Read More →</a>
** **the route is****
Route::get('single/blog/{id}','Web\Site\HomeController#show');
**the controller is**
public function show($id)
{
$posts = Post::findOrFail($id);
return view('site.home.singleblog',compact('posts'));
}
****the single section is****
#foreach($posts as $post)
<img class="img-responsive" src="{{asset("uploads/posts/$post->id/image/$post->image") }}" alt=""
{{ $post->name }}
{{$post->description}}
#endforeach
Your variable $posts is a single Post instance from Post::findOrFail($id) (where $id is coming from a route parameter, so a single value). You don't want to be iterating an instance of a Model. Use it in your view like a single model instance not a collection.
public function show($id)
{
view('site.home.singleblog', [
'post' => Post::findOrFail($id),
]);
}
Then in the view just remove the #foreach and #endforeach.
Try this:
{{ $post['name'] }} {{$post['description']}}
If you fetched $posts successfully, it should work. The error says $post is not an object but you are using object syntax to get value by key. So use array syntax.

Echo a Username via the ID of a user who isnt the Auth:: user in laravel

I know that you can echo a Auth User's name via
{{ Auth::user()->name }}
How can i echo a full list of all other users that are registered in the database??
Been trying for days to figure this out and i am struggling..
Thanks for any help!
there are many roads to get to Roam.
1: you can do this in your controller (loop throw all model columns):
$userNames = User::all();
return view('view')->with('userNames',$userNames);
and in your view :
#foreach($userNames as $name)
{{ $name->name }}
$endforeach
2: this is also a way to do it using ::pluk :
$userNames = User::pluck('name');
return view('view')->with('userNames',$userNames);
in your view :
#foreach($userNames as $name)
{{ $name }}
$endforeach
to sum up : the first way is used if you want to get data from more than 1 column second way is if you want to get data just from 1 column.
You can do it this way
In controller
$userNames = User::pluck('name');
return view('your-view', compact('userNames'));
in view
#foreach($userNames as $name)
{{ $name }}
$endforeach
So the User model is what Auth::user() retrieves for the current user.
You can imagine it as an equivalent to \App\User::findOrFail($user_id);
To get all users you can do \App\User::get();.
If you want to loop and echo out the names of all these users you could do something like:
$Users = \App\User::get();
foreach ($Users as $User) {
echo $User->name;
}

Trying to get property of non-object error, count always return 1 even no empty array

I am displaying my data using datatable, if empty array then datatable will not be shown.
I tried
#if(count($results) > 0)
//data show
#foreach($results as $r)
<p>{{$r->name}}</p>
#endfor
#else
No result found.
#endif
//
// $results is an array
This will return error if empty $result. How can i make it if $result is empty then show the custom message and not to display DataTable.
You should try this:
#if(isset($results) && !empty($results))
<?php
print('<pre style="color:red;">');
print_r($results);
print('</pre>');
?>
#foreach($results as $r)
<p>{{$r->name}}</p>
#endforeach
#else
No result found.
#endif
We do have a shorthand in blade for the foreach/empty scenarios.
#forelse ($results as $r)
<p>{{ $r->name }}</p>
#empty
No result found
#endforelse
From the code you have and the comment you have of how you get $results, $results should be an array of stdClass objects, which means that error should not be happening. Since the code you have is limited, I can't be sure the error is coming from that code at all.
My guess is that $results isn't an array but is an object. count(new stdClass) === 1 count(new App\User) === 1, etc ...
You are ending the foreach loop with endfor. It should be ended with endforeach.
If this do not fix your error then please update your question with your controller code. Is your results variable a collection object?
Maybe is safer to check at the controller level and return 0 if $result is NULL
After you get the collection just check this:
$result = $result ? $result : 0
And return $result.
Use isEmpty() to check object empty or not-
#if (!$result->isEmpty())

New to Laravel - How to pass model data to a blade view?

Ok, I am totally re-writing this question, now that I am a bit more familiar with larval.
Here is my situation: I have a guitar lessons site based on larval 5.2.36, where each lesson belongs to a category, and within a lesson are several exercises. An exercise table does not have a category id as it is linked to a lesson which has a category.
Goal What I am trying to figure out is how to pass the category of the currently displayed lesson or exercise to a menu sidebar view that displays the categories, so that the category of the lesson or exercise is highlighted. For this, I need to understand how to do such a task in laravel.
From what I gathered, this is often done via controllers. However, there is no menu controller, but rather a menu composer. It contains a function
class MenuComposer
{
public function compose(View $view)
{
$minutes = 6 * 60;
$value = Cache::remember('menu-categories', $minutes, function() {
return \App\Category::with('parent')->with('children')->get();
});
$view->with('categories', $value);
}
}
Then in the menu blade file we have
#foreach ($categories as $category)
<?php $category = $category->present(); ?>
#if ($category->parent == null)
<li>{{ $category->title }}</li>
#foreach ($category->children as $child)
<?php $child = $child->present() ?>
<li class="level1">{{ $child->title }}</li>
<?php
/*
#foreach ($child->children as $grandChild)
<?php $grandChild = $grandChild->present() ?>
<li class="level2">{{ $grandChild->title }}</li>
#endforeach
*/
?>
#endforeach
#endif
#endforeach
So this is clear. I see that I can use the menu composer to pass additional data with a $view->with() call.
The question is how do I get the current category? For exercises and lessons, the routes don't have category data. They are of form
lesson/lessonid/lessontitle
or
exercise/exid/extitle
So I know I could do some sort of query of the model. But seems that wouldn't make sense, since I know there are other places in the process flow where the current cat is being passed. For instance, on an exercise page, the view is retrieving category as
$exercise->lesson->category->title
It is being passed this in exercise controller as
public function index($id, $name = null)
{
//$this->hit($id);
$exercise = $this->apiController->get($id);
$authorized = $this->isUserAuthorized();
return view('exercise/index', [
'exercise' => $exercise->present(),
'authorized' => $authorized,
]);
}
Similarly, a lesson controller passes $lesson object to lesson view as
public function index($id, $name = null)
{
//$this->hit($id);
$lesson = $this->apiController->get($id);
$subscribed = $this->request->user() && $this->request->user()->subscribed('premium');
return view('lesson/index', [
'lesson' => $lesson->present(),
'subscribed' => $subscribed,
]);
}
Based on above, seems I could modify the return statements in the lesson and exercise controller to pass the category to the menu view, but I don't see in the documentation how to do that, and I suspect the menu view is rendered before the lesson and exercise controller are called...
Also read about using service providers. middleware, etc, here: How to pass data to all views in Laravel 5?
But all these approaches seem overkill. I don't need every view to have the data. Seems to me, I need to do this somehow in the menu composer. But I don't know what method to use from the menu composer to retrieve the current lesson or exercise category. In the menu composer after debugging in phpstorm I see that the $view object for a lesson has $view->$data->$lesson->$entity.
So what I did was edited the menu composer to pass category to view:
$d=$view->getdata();
$s=array_key_exists ('lesson' , $d );
if ($s ==1) $attr = collect($d)->get('lesson');
$cat=$attr->cat();
This works since in the LessonPresenter I added function
public function cat()
{
$cat = $this->entity->category['attributes']['title'];
return $cat;
}
This works, but I feel like it is a hack. And I will have to do this for the Exercise Presenter as well. Being new to larval I suspect there has to be a more elegant way to do this. So can someone please explain how this should be done?
thanks,
Brian
You can use Facades of Laravel directly in blade templates.
Just use {! !} syntax to try and echo it. e.g: {!! Route::current() !!}
There are also similar functions of Route facade you can use.
Then, you can check your category with #if() ... #endif blocks and add something like class name within it.
Note: Don't put lots of logic in your blade files. Do it in your controller file (even in your other service classes) and pass simplest variables (e.g $isCurrentCategory) as an array to your template files using View::make() function's 2nd parameter.
Maybe this can help you
<a href="#" class="{{ (\Request::route()->getName() == 'routename') ? 'active' : '' }}">
You can also get the route prefix for example, you can check this out here:
Laravel API Docs Routing

Pass sql result from controller to views in laravel

I'm having a problem to get my data from controller into my view, and I was hoping someone could help me.
Here is the code for my controller:
$Info = new Info();
$Info = DB::select('SELECT * FROM 'tblinfo');
and I only echo it in controller because my value results doesn't pass into the view, here's the additional code for my controller:
foreach ($Info as $Infos)
{
echo $Infos->fname;
echo $Infos->gender;
}
$data['result'] = $Infos->fname;
$data['result'] = $Infos->gender;
$this->view = View::make(App::make('web')->makeDeviceVersionPath('.').'.infofolder.infofile', $data);
Here is the code for my views:
#foreach $result as $info
{{ $info->name }}
{{ $info->gender }}
#endforeach
I hope someone could help me to pass my sql result to my views. Thank you! :)
if u have model u dont need to type raw sql code
just do like this
$info= Info::all();
return View('Index.index')->with('info',$info); // use ->with('*',$*) to send data to view
// Index is View folder
// .index is view name
Now in view grab $info data with for each
#foreach($info as $infodata)
<h3>{{ $infodata->name }}</h3>
<h3>{{ $infodata->gender}}</h3>
#endforeach
Adnan's answer is ok.
Op you should really check Eloquent and Response documentation from laravels website.
http://laravel.com/docs/4.2/eloquent
http://laravel.com/docs/4.2/responses

Resources