How to get the username through an id in Laravel? - php

I am trying to create an offers forum, where some user can create their offers in order to provide their services and I want to show the name of the person that created that offer instead of the id.
In my database I have the two tables:
Offers table:
User table:
In offers I have a column of the professor_id, that is related to the id of users table.
This is what i have in my controller to show the offers:
public function ofertes(){
$ofertes = Oferta::all()->sortByDesc('id');
return view('create.ofertes')->with(compact('ofertes'));
}
and in the blade.php I have that code:
#foreach($ofertes as $oferta)
<tr>
<td>Nom : {{$oferta->professor_id}}</td> <br>
<td>Títol : {{$oferta->titol}}</td> <br>
<td>Descripció: {{$oferta->descripcio}}</td> <br>
<td>Data: {{$oferta->created_at}}</td> <br><br>
</tr>
#endforeach
and that is what is shown:
Where it says nom, how I can show the name instead of the id?
Thank you!

If you have specified the relationship to professor in your Oferta model you can use the following code:
public function ofertes(){
$ofertes = Oferta::with('professor')->latest()->get();
return view('create.ofertes')->with(compact('ofertes'));
}
Your blade:
#foreach($ofertes as $oferta)
<tr>
<td>Nom : {{$oferta->professor->nom}}</td> <br>
<td>Títol : {{$oferta->titol}}</td> <br>
<td>Descripció: {{$oferta->descripcio}}</td> <br>
<td>Data: {{$oferta->created_at}}</td> <br><br>
</tr>
#endforeach
If you haven't specified the relation you should add the following method to your Oferta model (you might need to tweak this a little bit based on your namespaces):
public function professor()
{
return $this->belongsTo(User::class);
}

Very easy
public function ofertes(){
$ofertes = Oferta::with('professor')->latest()->get();
$users = User::all();
return view('create.ofertes')->with(compact('ofertes', 'users'));
}
In blade file:
<td>Nom : #foreach ($users as $user)
#if ($oferta->professor_id === $user->id) $user->nom $user->cognom
#endif
#endforeach
</td><br>

Join two table like
$oferta = DB::table('users')
->join('offers','users.id','=','offers.professor_id')
->select('offers.*','users.nom')
->orderby('offers.id','DESC')->get();
Then in place of {{$oferta->professor_id}}, replace {{$oferta->nom}}
Your problem should be solved

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

Get the amount of the bill in the class method

Sorry for my English.
I want to make a record that would be deduced me the sum of all my orders, that is, folded string of orders and drew grouped by orders.
I have created a model "Sale", which comprises method AmountOrder
public function AmountOrder()
{
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(price*quantity) as total_sales'))
->value('total_sales');
return $AmountOrder;
}
and to deduce the code like this
#foreach ($sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->client->name }}
</td>
<td>
{{$sale->date}}
</td>
<td>
{{$sale->AmountOrder($sale)}}
</td>
<td>
{{$sale->debt($sale)}}
</td>
<td>
{{$sale->date_of_issue}}
</td>
</tr>
#endforeach
But the problem is that the query is performed on each line. I'm new to Laravel, but thought maybe you can solve this problem somehow more beautiful?
Thank you very much in advance!
You are probably talking about the Eager Loading.
From the docs:
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.
However, you will be not able to use the Eager Loading now, with this code in the AmountOrder method.
A simple google search, also, led me to this example of Eager Loading with aggregate functions/relationships.
It will be probably a good start to think and implement your solution.
you have wrong in your select :
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(sale_lines.price*sale_lines.quantity) as total_sales'))
->value('total_sales');
My relationship
class Sale extends Model
{
//Получаем товар в этой продаже
public function good()
{
return $this->belongsTo('App\Good');
}
}
class Good extends Model
{
//В каких закупках был этот товар
public function purchases()
{
return $this->hasMany('App\Purchase');
}
//Продажи с этим товаром
public function sales()
{
return $this->hasMany('App\Sale');
}
}
Is it correct?
In my model i create method
public function AmountOrderRelation()
{
return $this->belongsTo('App\Good')
->selectRaw('sum(price) as aggregate, id')
->groupBy('id');
}
In controller
$new_sales = Sale::with('AmountOrderRelation')->get();
#foreach ($new_sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->AmountOrderRelation }}
</td>
</tr>
#endforeach
But my relations is null. What's my mistake?
I did it!
public function AmountOrder()
{
return $this->HasOne('App\SaleLines')
->join('goods', 'sale_lines.good_id', '=', 'goods.id')
->selectRaw(DB::raw('SUM(price*quantity) as aggregate, sale_id'))
->groupBy('sale_id');
}
public function getAmountOrderAttribute()
{
// if relation is not loaded already, let's do it first
if ( ! array_key_exists('AmountOrder', $this->relations))
$this->load('AmountOrder');
$related = $this->getRelation('AmountOrder');
// then return the count directly
return ($related) ? (int) $related->aggregate : 0;
}
And in controller
$sales = Sale::with('AmountOrder')->get();

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

relationship and blade in laravel

I have 3 table as mentioned below.
Table 1(user):
id username password Name Age
Table 2(tasks):
id task_name description
Table 3(logs)
id user_id task_id date hours
Table Relationships:
user has_many logs
task has_many logs
logs belongs_to user
logs belongs_to task
what i am trying to achieve is to get the logs with the user Name, task Name, date and hours.
Controller:
return View::make('log.index')
->with('logs',log::all());
Blade template
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>{{$log->users()->name}}</td>
<td>{{$log->tasks()->name}}</td>
<tr>
#endforeach
but unable to fetch users Name and Tasks name from the respective table. any help is appreciated.
A better way is to define inverse hasMany relation in your Model, as documented here
So in your logs model, probably you need to define:
class Log extends Eloquent {
protected $table = "logs";
public function user(){
return $this->belongsTo('User');
}
public function task(){
return $this->belongsTo('Task');
}
}
Then in your view you can either use :
$log->user()->first()->name
or even better, by using Dynamic Properties:
$log->user->name
$log->users() and $log->tasks() returns a query object. Below, each call returns the result which is the same as calling $log->users()->get() and $log->tasks()->get(). Because the relationships are many to many, you'll need to iterate over $log->users and $log->tasks to retrieve each record.
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>
#foreach($log->users as $user)
{{$user->name}},
#endforeach
</td>
<td>
#foreach($log->tasks as $task)
{{$task->name}},
#endforeach
</td>
<tr>
#endforeach
If you want a specific user/task attached to a log you'll have to build a query.
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>{{$log->users()->where('id', '=', $userID)->first()->name}} </td>
<td>{{$log->tasks()->where('id', '=', $taskID)->first()->name}} </td>
<tr>
#endforeach

Categories