Laravel 4 - Getting database results into a view - laravel

Im having a bit of trouble learning to get my data into my view, and i was hoping someone could help me.
I have the following function in my model
public function getPrivateMessages()
{
$userId = Auth::user()->id;
$messages = DB::table('pm_conversations')
->where(function($query) use ($userId) {
$query->where('user_one', $userId)
->where('user_one_archived', 0);
})
->orWhere(function($query) use ($userId) {
$query->where('user_two', $userId)
->where('user_two_archived', 0)
})
->get();
}
How would i pass it to my controller, then into my view?
Im a bit lost.
Thanks

Assuming that this is your Conversation model, you need to return those messages you queried:
public function getPrivateMessages()
{
...
return $messages;
}
Use it in your controller to pass to your View:
class HomeController extends Controller
{
public function index()
{
$conversation = Conversation::find(1);
return View::make('index')->with('privateMessages', $conversation->getPrivateMessages());
}
}
And in your view show whatever you need to:
<html><body>
#foreach($privateMessages as $privateMessage)
{{$privateMessage->text}}
#endforeach
</body></html>

In your controller, you would call this in one of your actions:
$pms = MyModel->getPrivateMessages();
return View::make('layout')
->with('pms', $pms);
Note that MyModel should be replaced with the actual name of your model. The ->with('pms',$pms) bit says, pass the contents of the variable $pms to the 'layout' view and assign it to a variable named 'pms' in that view. Feel free to customize the name of the view to match whatever view you want to use and pick different variable names if you are so inclined.
Then, in your view you would use it like this:
#foreach($pms as $pm)
<p>From: {{ $pm->user_one}}</p>
<p>{{ $pm->message }}</p>
#endforeach
Here, we're just looping over each of the private messages and outputting a few fields (user_one and message, you'd want to use the names of whatever columns you have in the database).
For more info see these sections of the docs:
Views
Basic controllers

inside your view
<?php $var=DB::table('tablename')->get(); ?>
#foreach($var as $variable)
{{ $variable->tablefield }}
#endforeach
here we are accessing the table named 'tablename' from our database (abbrievated as DB) and then accessing all the columns of the table through get method. Then we are storing them in a random variable (say var so the that we can loop it easily). And then we are simply looping through to print our column data(as in the case above)

Related

How to fix Laravel resource is not working properly in blade view?

I'm confused why casted props are inaccessible in the blade file. When I try to check it in the controller its showing properly.
Here's the JSON shown in the browser: return $users; (here status is string)
But when I tried to show it in the view, the status goes back to int which is the original value.
#foreach ($users as $user)
<h1>{{ $user->status }}</h1>
#endforeach
And when I tried to dd in the blade view it shows the original model values.
Here's my resource file (shortened version):
public function toArray($request)
{
return [
'status' => StatusEnum::value($this->status),
...
];
}
Here's my controller look like:
public function index()
{
$record = User::all();
$users = UserResource::collection($record);
return view('pages.user.index', compact('users'));
}
I already tried solutions from other related QA e.g. ->resolve() but not working properly.
Make sure user model doesn't has getStatusAttribute() function nor status() if it returns a related model.
Keep in mind that this may be due to inherited or imported classes and traits in User model

How to dynamically switch between two arrays for attribute in my blade template

I have a controller method which retrieves data from a Queue, the queue can have a relationship to either a Guest or a Customer model.
In my blade template I iterate over the Queue and need to display either Guest.Name or Customer.Name depending on which column is populated.
Controller
$queue = Queue::where('business_id', '=', $business_id);
$customer_bag = $queue->pluck('user_id');
$guest_bag = $queue->pluck('guest_id');
$customers = User::whereIn('id', $customer_bag)->get();
$guests = Guest::whereIn('id', $guest_bag)->get();
return view('myqueue', compact(['queue', 'customers', 'guests']));
Blade Template
#foreach($queue as $quee)
{{ $customers->find($quee->user_id) ? $customers->find($quee->user_id)->name : $guests->find($quee->guest_id)->name }}
#endforeach
When I use this and the guest_id is blank I get an error stating "Trying to get property 'name' of non-object". How can I correctly detect which one to use?
I think so many problems with your code.
Firstly, $queue is findOrFail() which returns a single object data(not array or collection that can be used for foreach.) I think you need to change to get()
Also $customers and $guests are a collection, so you can not use find() method.
Then you didn't define $quee in the #foreach, so it's will give error result.
I think this code will return as you expected if you fix above problems:
#foreach($queue as $quee)
{{ \App\Customer::find($quee->user_id)->name ?? \App\Guest::find($quee->guest_id)->name ?? "no name" }}
#endforeach
But a better approach is using relation from your queue model:
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function guest()
{
return $this->belongsTo(Guest::class);
}
public function getNameAttribute()
{
return $this->customer?$this->customer->name:($this->guest->name??"no name");
}
and in the blade view
#foreach($queue as $quee)
{{ $quee->name }}
#endforeach
The issue turned out to be that one of my test data records didn't have a value in the guest_id when it should have, this caused the blade template to fail render.

Laravel: Passing data to view through route after querying

I recently asked a question about defining many to many relationships (using belongsToMany) and it was a huge help. So now in my models I have:
Users model
public function subjects()
{
return $this->belongsToMany('App\Subject', 'users_subjects', 'user_id', 'subjects_id');
}
Subjects model
public function users()
{
return $this->belongsToMany('App\User', 'users_subjects', 'subject_id', 'user_id');
}
This way I establish a relationship between users and subjects via the users_subjects table. My next step was to create a controller, SubjectsController, which ended up looking like this:
class SubjectsController extends Controller
{
// returns the view where subjects will be displayed
public function index()
{
return view('profiles.professor.prof_didactic_subjects');
}
// get users with subjects
public function getSubjects()
{
$subjects = User::with('subjects')->get();
}
// get a single user with a subject
public function getSubject($id)
{
$materia = User::where('id', '=', $id)->with('subjects')->first();
}
}
I'm not very sure about the code in the controller though.
The final step is where it gets tricky for me, even after reading the docs: I want to pass each result to the view, so I can have multiple tiles, each populated with data from subjects the user is associated with:
#foreach ($subjects as $subject)
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title">{{ $subject['name'] }}</p>
<div class="content">
<p>{{ $subject['description'] }}</p>
</div>
</article>
</div>
#endforeach
I tried many different route configurations, but kept getting either the undefined variable error or trying to access non-object error.
What's the proper course of action here? I feel I'm missing something very basic. Thanks in advance for any help.
The answer
The solution provided below by #Sohel0415 worked perfectly. My index() method on the controller now looks like this:
public function index()
{
// temporary value while I figure out how to get the id of the current user
$user_id = 6;
$subjects = Subject::whereHas('users', function($q) use ($user_id){
$q->where('user_id', $user_id);
})->get();
return view('profiles.professor.prof_didactic_subjects')->with('subjects', $subjects);
}
My route looks like this:
Route::get('/professor', 'SubjectsController#index');
I was pretty lost, so this absolutely saved me, thanks again :)
You need to pass $subjects to your view. You can use compact() method for that like -
public function index()
{
$subjects = Subject::with('users')->get();
return view('profiles.professor.prof_didactic_subjects', compact('subjects'));
}
Or using with() method like -
public function index()
{
$subjects = Subject::with('users')->get();
return view('profiles.professor.prof_didactic_subjects')->with('subjects', $subjects);
}
If you want to get Subject for a particular user_id, use whereHas() -
$subjects = Subject::whereHas('users', function($q) use ($user_id){
$q->where('user_id', $user_id);
})->get();

How to pass variable from foreach to view in laravel 5.4?

I want to count each location in my Job table by using location_id in my job table with id in location table. below code, I can count result correctly but I don't know how to pass this variable to the view. Please help?
//my code
public function index(){
$location = Location::all();
$count_location = [];
foreach ($location as $locations){
$count_location = Job::where('location_id', $locations->id)->count();
}
}
Use withCount() and view() to pass location with counted jobs to the view:
public function index(){
return view('view.name', [
'locations' => Location::withCount('jobs')->get()
]);
}
In the view:
#foreach ($locations as $location)
{{ $location->name }} has {{ $location->jobs_count }} jobs
#endforeach
You can return the collection of locations to the view and then loop through each object in the collection like so:
return view('index', [
'locations'=> $locations,
]);
Then in your index.blade.php you can use something like a #foreach or #forelse loop
#foreach ($locations as $location)
{{ $location->id }}
#endfoeach
EDIT
From the looks of it you would be better off defining a relationship between locations and jobs (i.e. a "many to many" or "one to many" relationship). this would allow you to get the counts for jobs at given locations very easily like so:
$location->jobs->count()
Eloquent relationships are explained in the documentation here
https://laravel.com/docs/5.5/eloquent-relationships
It would be more efficient if construct your query to fetch the count of related models instead of looping through all the results.
Have a look at Counting Related Models in the documentations.
For example, to get the count of all jobs related to a location, you could do:
$locations = App\Location::withCount('jobs')->get();
foreach ($locations as $location) {
echo $location->jobs_count;
}
You need to adjust the code according to your models structure.
Do this
public function index(){
$locations = Location::all();
return view('index', compact('locations'));
}
In your Location model make a relationship by adding this
public function jobs(){
return $this->hasMany(Job::class);
}
In your index view do this
#foreach ($locations as $location)
{{$location->jobs->count}}
#endforeach
Please note that Job should be there in your your model

How do I use Eloquent ORM to retrieve data from a database in Laravel

I'm new to MVC and do not understand it very much at all. I have a database with one table called products
I have a Model called Productwhich looks like
<?php
class Product extends Eloquent {
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
// we only want these 3 attributes able to be filled
protected $fillable = array('type', 'brand', 'image');
}
I have a Route like so
Route::get('products', function()
{
return View::make('products');
});
And my View looks like this
#extends('master')
#section('content')
PRODUCTS
#foreach($products as $product)
{{ $product->type }}
#endforeach
#stop
I see you can get all the rows like so $products = Product::all(); but I don't understand WHERE this goes. Does it go in the View? Does it go in the Model? Does it go in the Route? My current #foreach loop just results in an undefined variable: products
Can someone please clarify?
This should get you started for now:
Route::get('products', function()
{
$products = Product::all();
return View::make('products')->with('products', $products);
});

Resources