laravel one to one retrieve many results - laravel

I have business and location table and they have one to one relationship. Everything works fine so far but they problem is I only find 1 result.
However business_id which is a foreign key in location table has loads of results.
My business table has id from 5-95 and these are the records I want to return
so in my location table I also have business_id which is from 5-95.
How do I tell eloquent to retrieve these specific records?
At this moment I have:
function transportProfile() {
$type = 2;
$business = Business::where('type', $type)->get();
$location = Business::find(3)->locations;
echo $location;
return view('userProfile', compact('business', 'location'));
}
So to clarify business table has id from 5-95 and location table has business_id from 5-95 I want to return results from those 2 tables so I can use it in view

Use the eager loading:
$businesses = Business::where('type', $type)->with('location')->get();
To display the data:
#foreach ($businesses as $business)
{{ $business->location->name }}
#endforeach

Related

Retrieving data from table with multiple row

I am currently having trouble retrieving the data from a table based on their id. Here the $content will pluck multiple ids from the table. When retrieving the ModuleDevelopment table, it retrieves all of the data without organizing by their id. What should I do to separate the status based on their id?
$content = ModuleListing::where('sme_role', $selectedRole)
->get()->pluck('mit_id');
$stats = ModuleDevelopment::whereIn('mdev_mit_id', $content)
->orderBY('mdev_mit_id','desc')->get()->pluck('mdev_status');
result of $stats
result of $content
Just an update of the coding I previously had trouble with, the main issue was to organize the status of each module development based on their ID,
therefore, the code I had was
this was at my controller:
$moduleDev = ModuleDevelopment::select('mdev_mit_id','mdv_sts')
->whereIn('mdev_mit_id', $content)
->orderBY('mdev_mit_id', 'asc')
->get();
and this is what was on my blade.php
#foreach($moduleDev as $modDev)
#if($listing->mit_id == $modDev->mdev_mit_id)
#if($modDev->mdv_sts == 'complete' )
{{'Complete'}}
#elseif($modDev->mdv_sts == 'incomplete')
{{'Incomplete'}}
#endif
#endif
#endforeach
I hope it is right and helpful for other people.

laravel tables with relationship and insertion

I have 4 tables
Customers : with data of customers. this table hasMany(Refunds)
Refunds: with data of various request. this table belongsTo(Customers) AND belongsToMany(Services)
Services: with list of services. this table belongsToMany(Refunds)
Refunds-Services: bridge table for refunds and services
I have a form that must insert datas in the correct table.
public function storeRefunds(RefundsPost $request){
DB::beginTransaction();
$customers = Customers::create($request->all());
$refunds = $customers->refunds()->create([
'date_ref' => request('date_ref'),
'status_ref' => request('stato'),
]);
$tipo = $request->input('tipo', []);
$importo = $request->input('importo', []);
$refunds = Refunds::create($request->all());
for ($i=0; $i < count($tipo); $i++) {
if ($tipo[$i] != '') {
$refunds->services()->attach($tipo[$i], [
'services_id' => $tipo[$i],
'services_amount' => $importo[$i]
]);
}
}
return redirect("/");
}
with this code i can insert all datas in correct tables but i cannot find ID connection in the Refunds table. Two different ID are created in Refunds table. second created id in the Refunds table not connected to any customer (0) but connected to the list of services choosen.
How can i do?
Thx
You need to debug your code. First Refund creates in this line $refunds = $customers->refunds()->create and it's belongs to Customer, second Refund creates here : $refunds = Refunds::create($request->all()); and it's doesn't relate to any Customer, but relates to Service (you do this in for loop). By the way, your tipo input is not multiple (it should be with [] if you expects it can be more than one value) and for loop is senseless in this sutiation.
Delete one of Refunds::createmethods, bring your data to expected view and use createMany() method.
More info in Laravel docs : https://laravel.com/docs/7.x/eloquent-relationships#the-create-method

How to make this Eloquent relationship in Laravel

I have a table called users with a column username. Another table called students with a column code. I have made a hasMany relationship in User model like below and it's working fine.
public function students()
{
return $this->hasMany(Student::class,'code','username');
}
I have another table called institutes where a column is similar to students table named inst. I need to show data from institutes table while showing data of an user. How to make this relationship?
users table
username|mobile|address|password
students table
username|name|inst|roll|reg
institutes table
name|inst|address|phone
This is my home controller
public function index()
{
$admins = User::where('username','=',Auth::user()->username)->get();
return view('home', compact('admins'));
}
And this is my view
#foreach($admins as $key => $admin)
#foreach($admin->students as $student)
{{ $student->reg }}
#endforeach
#endforeach
Add migration to your Students table :
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('set null');
Update your model User on students method :
return $this->hasMany(Student::class);
Add "with method"
$admins = User::where('username','=',Auth::user()->username)->with('students')->get();

How to get data from additional table in many to many relationship?

I have a many to many relationship between tables 'products' and 'recipes'. I created table product_recipe to handle this and my table looks like:
id | recipe_id | product_id | amount
In my blade file I use
#foreach($recipe->product as $row)
<p>{{ $row->name }}</p>
#endforeach
to get a name of used products in recipe. How I can get an amount of product which is stored in product_recipe table? Do I have to create a model for product_recipe table and get it from model?
You will have to declare the relationship wants to include the extra pivot information so that the pivot object that is attached to the records will have more than just the 'id's:
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('amount');
}
Now the pivot object will include the field amount:
foreach ($recipe->products as $product) {
echo $product->pivot->amount;
}
"By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship"
Laravel 6.x Docs - Eloquent Relationships - Many To Many - Retrieving Intermediate Table Columns withPivot
You have to use pivot attribute.
#foreach($recipe->product as $row)
<p>{{ $row->pivot->field_name}}</p>
#endforeach
No need to create Model for product_recipe. Just specify table name in relation of two Models.
Like return $this->belongsToMany('App\Product', 'product_recipe')->withPivot('amount'); and similar for other model.

Laravel - Get users name from ID

I have a Laravel 5.6 app that is logging various information into a database table, I am then displaying this data in a HTML view. I am calling this view like this...
$logs = Log::all();
return view('logreport.index')->with('logs', $logs);
The table only contains the user ID, is there a way to get the users first name and last name for the users table? Or do I need to set a relationship up?
if the log table contain the user_id and you want to get user name you can get the user name through relation as the following:
in log model add the following method:
public function user(){
return $this->belongsTo('App\User','user_id','id');
}
and then you can access the user information in view file such as firstname as the following
#foreach($logs as $log)
<h1>{{$log->user->first_name .' '.$log->user->last_name }}</h1>
#endforeach
You don't need to set a relationship. Just use eloquent.
$users = User::whereIn('id', array(...))->get();
Or with query builder
$users = DB::table('users')->whereIn('id', array(...))->get();
Replace the dots by the values of your IDs
You can use Eloquent relationship as answered by Ali or you can use "Joins" with your result as:
$logs = Log::join('users', 'users.id', '=', 'logs.user_id')->get();
return view('logreport.index')->with('logs', $logs);
and then access the result as:
<h1>{{ $log->first_name .' '. $log->last_name }}</h1>

Resources