Laravel 5 Model Relation to Query in blade - php

Schema User Table
ID|NAME
1 |John
2 |Doe
Schema Financial Table
ID|USER_ID|PROFIT |DATE
1 |1 |1000 |2016-12-22
2 |2 |-2000 |2016-12-22
3 |1 |2000 |2016-12-24
4 |2 |-2000 |2016-12-24
User Model
class User extends Model
{
public function Financial()
{
return $this->hasMany('App\Financial');
}
}
Financial Model
class Financial extends Model
{
public function financial()
{
return $this->belongsTo('App\User');
}
}
My Controller
class MyController extends Controller
{
public function index()
{
$user = User::get();
$financial = Financial::get();
return view('page.index',compact('user','financial'));
}
}
My Blade
#foreach ($user as $u)
<tr>
<td>{{$u->id}}</td>
<td>
{{$u->financial->sum('gross')}}
{{-- Above code doesn't work --}}
{{-- Run something link --}}
{{select (sum(profit) as total) from financial where user_id = $u->id}}
</td>
</tr>
#endforeach
QUESTION
How can i achieve that select from my blade? i'm planning to use #inject('DB','Illuminate\Support\Facades\DB') so i can use DB::raw in my blade, but i'm confused on how to execute the query to achieve the select :(

Solved by using Laravel Collection Method Pluck and Laravel Blade Service Injection.Below is the code i've done to archive what i want:
#inject('financial','App\Financial') {{-- inject before foreach --}}
#foreach ($user as $u)
<tr>
<td>{{$u->id}}</td>
<td>{{$financial->where('user_id','=',$u->id)->get()->pluck('profit')->sum()}}</td>
</tr>
#endforeach
To Evaluate what happen:
$financial->where('user_id','=',$u->id)->pluck('profit')->sum()
// get financial where user_id = $u->id // get the profit // sum the profit
Cheers!

You could have simply done this:
{{$u->financial()->sum('gross')}}
If you are running a query on a relationship, add function brackets while calling it.

Related

How can I get field_name from the first table using relationship between two models using laravel 6?

I have two tables with two models and make a reactionship to can get the field_name from the first table :-
First Model:
class KpcField extends Model
{
public function concession(){
return $this->hasMany(Concessions::class);
}
}
Second Model :
class Concessions extends Model
{
public function kpcField(){
return $this->belongsTo(KpcField::class);
}
}
And trying to retreive the field_name in concession view but it showed (Trying to get property field_name of non-object)
Using the foreach to show the data in table :
#foreach ($show_concessions as $show_concession)
<td> {{ $show_concession->kpcField->field_name}} </td>
#endforeach
You can Try This :
#foreach ($show_concessions as $show_concession)
#foreach ($show_concession->kpcField as $item)
<td> {{ $item->field_name}} </td>
#endforeach
#endforeach

Two array in one foreach Laravel

I have two table the first called codes, and second is company.
Codes table structure:
id| title | desc | company | order
Company table structure:
id| name
Here is code from my controller
$codes= DB::table('codes')->orderBy('company', 'ASC')->get();
$company = Company::all();
return view('codes.index',compact('codes', 'company'));
And here is codes from my view.
#foreach($codes as $code)
<tr>
<td>{{$code->title}}</td>
<td>{{$code->code}}</td>
<td>{{$company->name}}</td>
<td>{{$code->order}}</td>
</tr>
#endforeach
I can not get name of company. How is possible? Thanks for all
$services = Services::orderBy('company', 'ASC')->with('company')->get();
return view('services.index',compact('services'));
view
#foreach($codes as $code)
<tr>
<td>{{$code->title}}</td>
<td>{{$code->code}}</td>
<td>{{$code->company->name}}</td>
<td>{{$code->order}}</td>
</tr>
#endforeach
I did not know the names exactly because I wrote them because of that approximation.
If the company is defined as id, you can get company information using.
You just have to define this model in the service model.
public function company()
{
return $this->belongsTo(Companies::class);
}
Replace your view code with this
#foreach($codes as $key => $code)
<tr>
<td>{{$code->title}}</td>
<td>{{$code->code}}</td>
<td>{{$company[$key]->name}}</td>
<td>{{$code->order}}</td>
</tr>
#endforeach
And it'll work

Efficient way to handle date between Controller and view in laravel

I have an app that reads through a table of data and based on the name of the person, does a for each loop, producing a card for each job that is assigned to that user.
EG.
user1 Job 1
user1 Job 2
user2 Job 3
user3 Job 4
... could be 3000 plus records here with up to 40/50 users
The controller collects the data from the table and sends it in bulk to the view for a foreach user statment to produce the code for each user then for each Job where it matches the user.
Controller code:
function dash()
{
if($user = Auth::user())
{
$users= User::all();
$jobs= Job::all();
return view('jobview', compact('users','jobs'));
}
if(Auth::guest())
{
return redirect('/home');
}
}
The view code is simple:
#foreach($users as $user)
#foreach($jobs as $job)
#if ($job->technician == $user->id)
<!--The code in this include generates a few lines of code to create the card-->
#include('layouts/sublayouts.jobscard')
#endif
#endforeach
#endforeach
The core problem is, there can be over 3000 cards (all need to be visable at the same time) and there can be 40 users to show.
I assume the slowness is the for each loop being done in the view?
Any guidance would be appriciated.
Thanks
Matt
Try something like, this will do the comparasion when getting the data from the database instead, should be alot faster:
$user_id = Auth::user() -> id;
$jobs = Job::Where('technician', '=', $user_id)->get();
return view('jobview', compact('jobs'));
EDIT:
In response to comment for all Jobs, do an inverse One-to-many relationship, for example:
//Job Model
class Job extends Model
{
public function technician()
{
return $this->belongTo('App\User');
}
}
//Controller
$jobs= App\Job::All();
return('jobview', compact('jobs')
//View
#foreach($jobs as $job)
{{ $job -> technician -> [Insert Some User property you want here] }}
{{ $job -> jobName }}
And if you want to "group" them by user simply do orderBy('technician') in your controller.
Take a closer read here

laravel5.1 retrieve nested relation using eloquent hasOne() (one to one relation)

My table design is:
users: | id |username | ... |
tickets: | id | supp_id | ... |
ticket_replies: | id | ticket_id | user_id |
My controllers look like:
user:
public function tickets()
{
return $this->hasMany('App\ticket');
}
ticket:
public function ticket_replie()
{
return $this->hasMany('App\ticket_replie');
}
public function supporter()
{
return $this->hasOne('App\User', 'id','supp_id');
}
My controller looks like this:
$tickets = Auth::user()->tickets()->orderBy('status', 'desc')->paginate(2);
return view('protected.ticketsList', [
'tickets' => $tickets,
]);
In my view I use:
supporter: {{ $ticket['supporter']->username }}
Any idea where I do wrong? I get all the time this error:
Trying to get property of non-object
In my point of view the relation between the tables itself is done correctly.
When I use for example {{ dd($ticket) }} in my view I get an object with all the items I need:
So first of all, trying to access the function public function supporter() on your Ticket model cannot be done using array syntax. Change:
{{ $ticket['supporter']->username }}
to:
{{ $ticket->supporter()->first()->username }}
If you don't want to use the ->first() you can do one of two things. Modify your existing query to include the ->with("supporter") syntax:
$tickets = Auth::user()
->tickets()
->with("supporter")
->orderBy('status', 'desc')
->paginate(2);
And access the supporter from the view like so:
{{ $ticket->supporter->username }}
// Notice how supporter is no longer a `method` ->supporter() but a `property` ->supporter
Or you can modify your relationship to include the closer ->first():
public function supporter(){
return $this->hasOne('App\User', 'id','supp_id')->first();
}
And then access it like so:
{{ $ticket->supporter()->username }}
// Notice you no longer need `->first()`
So, as you can see, there are multiple ways to access a Ticket's Supporter. Please note that you can't really combine these options; modifying the function to include ->first() and then trying to use ->with() will return an error, so pick one or the other.
Hope that helps!

Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object

First time to try laravel eloquent relatioinstip
I know it's really simple but I am getting this error don't know what's wrong with it
I have 2 tables in data base, news and news_image
in database
Tables:
news
id | header | details
news_image
id | image | news_id
And have 2 models News , newsImage
newsImage model :
class newsImage extends Eloquant {
protected $table = 'news_image';
public function news()
{
return $this->belongsTo('News');
}
}
News model
class News extends Eloquent
{
protected $table = 'news';
public $timestamps = false;
public function image()
{
return $this->hasMany('newsImage');
}
}
The view:
foreach($news as $new)
<tr>
<td> {{$new->id}} </td>
<td> {{ $new->header}}</td>
<td> {{ $new->details }}</td>
</td> {{$new->news->image}}</td>
</tr>
when I run this it's get error :
Trying to get property of non-object (View: /var/www/html/clinics/app/views/news/index.blade.php)
Any ideas on what could be causing this error?
First, assuming what you are passing to your view is an array or Collection of News objects, you should probably be using $new->image to access the News Item relation. By defining the function image() in your News model, you can access the relation with either the ->image or ->image() calls. In either case, what you need to call is probably
$new->image->first()->image
To break that down:
->image gets the Collection of NewsImage relations
->first() gets the first item in the Collection
->image (the secone one) gets the image field from that NewsImage
If the Collection has more than one item, you can instead loop over it to get all of the images as shown in the other answer.
There are a couple things I would change:
In your News model, change the relationship from "image" to "images" since it's a one to many relationship. It just keeps your code clean.
Your foreach loop in your view should loop through all the news models, but remember that each news model has multiple images, so you should have another loop inside your existing loop to display the images, i.e. foreach ($new->images as $image)
#foreach ($news as $new)
<tr>
<td> {{$new->id}} </td>
<td> {{ $new->header}}</td>
<td> {{ $new->details }}</td>
<td>
#foreach ($new->images as $image)
{{ $image->image }}
#endforeach
</td>
</tr>
#endforeach

Categories