Many to many relations LARAVEL - php

I have a problem retrieving data from a third table, as you can see I have three tables:
Models : id , code , title
levels : id , code . title
models_level : model_id,level_id
I have as function :
$model = model::paginate(10);
$level = level::all();
$models_level = models_level::all();
return view('pg',compact('model','level','models_level'));
How can I retrieve the level name based on the model id retrieved?
Here is my blade
<tbody>
#foreach($model as $f)
<tr class="item{{$f->id}}">
<td style="font-size: 13px;"> {{$f->title}}</td>
<td style="font-size: 13px;">{{$f->code}}</td>
<td style="font-size: 13px;">{{$f->models_level->level_id}}</td>
</tr>
#endforeach
{{ $filiere->links() }}
</tbody>
I need to show the title in level instead of the ID.
in this case I have 2 different tables and the 3 rd is associative
table that contains the two , so I have to pass by model to get
model_level . get the level id depending on the model_id and the go to
level and find the title ..

Models
– id
levels
– id
models_level
– product_id
– shop_id
here models_level table is called as pivot table
app/Model.php
class Model extends Model
{
public function levels()
{
return $this->belongsToMany('App\level','models_level');
}
}
app/level.php
class Level extends Model
{
public function Models()
{
return $this->belongsToMany('App\Shop','models_level');
}
}
$model = model::with('levels')->paginate(10);
return view('pg',compact('model'));
<tbody>
#foreach($model as $f)
<tr class="item{{$f->id}}">
<td style="font-size: 13px;"> {{$f->title}}</td>
<td style="font-size: 13px;">{{$f->code}}</td>
<td style="font-size: 13px;">{{$f->levels[0]->id}}</td>
</tr>
#endforeach
{{ $filiere->links() }}
</tbody>
You can read more about many to many relationships in the docs.

I assume you are using a One to Many relationship and you have the correct methods in you model classes.
This way you can change your controller method to:
$model = model::with('level')->paginate(10);
return view('pq', $model);
and in your blade files loop:
<td style="font-size: 13px;">{{$f->level->title}}</td>
You should read up on eloquent relationships in the laravel documentation:
https://laravel.com/docs/6.x/eloquent-relationships

Related

Attempt to read property "nama" on int

im trying to get the latest data on database, im using this on my views :
#foreach ($shows as $s)
<tbody>
<tr>
<th scope="row">{{$loop->iteration}}</th>
<td>{{$s->nama}}</td>
<td>{{$s->umur}}</td>
<td>{{$s->alamat}}</td>
<td>{{$s->nama_ortu}}</td>
<td>{{$s->posyandu}}</td>
<td>{{$s->result}}</td>
</tr>
</tbody>
#endforeach
and on controller :
public function showresultpasien()
{
$shows = DB::table('pasiens')->orderBy('id', 'DESC')->first();
return view('result', compact('shows'));
}
did i doin something wrong ?
The name of the function in the model cannot be the same as the name of a field in your table. Also in my case the column names do not follow the laravel/eloquent nomenclature so another parameter is added to belongsTo with the field name

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