How to Update one form data to different tables in Laravel? - php

I am working with Laravel 5.6 and MySQL. in My app I have some data edit form and its updated values saving with 3 different tables. called vehicles, cars and upload My edit form url as following,
http://localhost:8000/myads/1/edit
number (1) is vehicle table id number, like this,
id name owner
1 toyota dane
2 BMW peter
3 Benz samantha
4 volvo Alex
and car table is like this,
id fuel vehicle_id
1 P 1
2 D 3
3 E 2
I need update cars table data with regarding to vehicle_id , My VehicleController vehicle table data update function is like this
public function update(Request $request, $id)
{
$vehicle = Vehicle::find($id);
$vehicle->name = $request->input('name');
$vehicle->owner = $request->input('owner');
$vehicle->save();
}
now I need update cars table fuel values with same form optional values input. how can I do this in the Controller?
My fuel selection input is like this,
<div class="form-group">
<label for="exampleFormControlSelect1">Fuel</label>
<select class="form-control" id="fuel" name="fuel">
#foreach($vehicles->cars as $car)
<option value="{!! $car->fuel !!}">{!! $car->fuel !!}</option>
#endforeach
<option value="P">Petrol</option>
<option value="D">Diesel</option>
<option value="H">Hybrid</option>
<option value="E">Electric</option>
</select>
</div>
relationship among Vehicle and Car Models are
Vehicle Model
public function cars()
{
return $this->hasMany(Car::class);
}
Car Model
public function vehicle()
{
return $this->belongsTo(Vehicle::class);
}
How can do it?

Use a hidden Input field (load car id to the input using $car->id ) in form and name it as 'car_id'.
In the same update function,
$carId = $request->input('car_id');
$car= Car::find($carId);
//Update details here
$car->save();
Note : when you are working with multiple table, do not forget to use DB Transaction.

got success with following codes,
$vehicle->cars()->where('vehicle_id', $id)->update(['fuel' => $request->input('fuel')]);

Related

How to exclude certains columns while using eloquent | Laravel

i have an group table. My main table. So i have group_hotels table this table is a pivot table. (id, group_id, hotel_id)
Now in my blade group edit page, i want to list before added pivot table like this code:
My Group model:
public function hotels(){
return $this ->belongsToMany('App\Models\Hotel','group_hotels');
}
My controller:
$group = Group::find($id);
$hotels=Hotel::all();
My blade hotel select2 field:
#foreach($hotels as $hotel)
<option value="{{$hotel->id}}">{{$hotel->name}}</option>
#foreach ($group->hotels as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
#endforeach
The output like this: http://prntscr.com/10v13ed
Now what i want to do, in my group_hotels pivot table, if hotel id exist in group_hotels except the in the pivot table id nothing come hotel table.
In short: If the hotel_id part in the group_hotels table is present in my hotel table, I do not want to call it in the hotel variable.
One option you have is to exclude the Hotel's you don't want in your list at the query level:
Hotel::whereNotKey($group->hotels->modelKeys())->get();

Problem with retrieving selected checkboxes from database in Laravel

I am trying to retrieve all checkbox values from database and those values that are selected need to be checked. I have many to many relationship between models and I currently am able to retrieve all values from database and to write them in blade or those values that are just selected (it is one OR the other) but I can't seem to find solution to retrieve them all that exist in database and those that are selected to be checked. Any help is appreciated. Here is my code and database tables.
user_profiles table
id user_id first_name
1 1 Mike
sport table
id name
1 Football
2 Basketaball
3 Handball
4 Etc...
user_sport table
id user_id sport_id
1 1 1
2 1 2
UserProfile.php
public function sports()
{
return $this->belongsToMany(UserSport::class, 'user_sport', 'user_id', 'sport_id');
}
UserSport.php
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_sport', 'sport_id', 'user_id');
}
UserProfileController.php
public function showProfile($username, Request $request)
{
$profileId = User::getIdFromUsername($username);
$sportsOptions = UserSport::get();
$userSportsOptions = UserProfile::findOrFail($profileId)->sports()->get();
return view('profile.show', compact('sportsOptions', 'userSportsOptions'));
}
show.blade.php
#foreach($sportsOptions as $sportsOption)
<label class="checkbox-inline">
<input type="checkbox" id="sport" name="sport[]" value="{{$userSportsOptions->id}}"> {{$userSportsOptions->name}}
</label>
#endforeach
So, I know that naming conventions aren't great but relationship works and with foreach and $sportsOptions in blade in this case and example it displays all four values from sport table and with $userSportsOptions it displays those two values (selected values). I need help on how to achieve that displays in blade all values and those that are selected to be selected.
#foreach($userSportsOptions as $userSportsOptionRow)
$selectedIds[] =$userSportsOptionRow->sport_id;
#endforeach
$userSportsOptions->id
#foreach($sportsOptions as $sportsOption)
<label class="checkbox-inline">
<input type="checkbox" id="sport" name="sport[]" value="{{$sportsOption->id}}" #if(in_array($sportsOption->id,$selectedIds))> {{$sportsOption->name}}
</label>
#endforeach```

how to merge two column values as option values for dropdown using Laravel query

I have two tables for example
table_A, table_B
table_A
id username
5 kumar
6 pavan
table_B
id userid rname
1 testing
2 5 --
3 newtest
4 6 --
what i want is
<select>
<option value='1'>testing</option>
<option value='2'>kumar</option>
<option value='3'>newtest</option>
<option value='4'>pavan</option>
</select>
if rname is empty means (--) so based on userid from table_B, get username from table_A, so how do we display using laravel query with pluck
Use Laravel belongsTo() relationship. Make two model as TableA and TableB. In TableB model, make a relationship to TableA like-
public function tableA()
{
return $this->belongsTo(TableA::class,'userid');
}
And then in your controller-
$tableb_datas = TableB::with('tableA')->get();
return view('your_view')->with('tableb_datas', $tableb_datas);
And last in your view-
<select>
#foreach($tableb_datas as $b)
#if($b->rname!="--")
<option value='{{$b->id}}'>{{$b->rname}}</option>
#else
<option value='{{$b->id}}'>{{$b->tableA->username}}</option>
#endif
#endforeach
</select>
You can use merge function. The merge() method merges the given array or collection with the original collection.
$first = table_A::all();
$second = table_B::all();
$finalResult = $first->merge($second);
$result = $finalResult->all();
$finalResult->each(function($record) {
echo $record-><fieldName>.'<br />';
});
Hope this helps you!

display specific data from function (laravel)

I'll explain my structure first so you can understand what I'm trying to get
1 - Car = name - model - age
2 - User = name - city - phone
3 - Reservation = from_date - to_date
4- reservation_user = user_id - reservation_id
5 - car_user = user_id - car_id
In the view.blade I tried to show the user's info in a table and below that the user request car's descriptions ( he wants to buy) and below that if he has a car he wants to rent (ONLY rent)
table user's info
table with all the cars he request ( both rent and buy)
table with car id and the dates the user want the car from-to
public function show($id)
{
$users = User::with('cars')->where( 'id',$id)->get();
return view('show')->withusers($users);
}
the way I saved the cars for sales
$id = $new_cars->id;
$user->cars()->attach($id);
for rent
$id = $new_car->id;
$R_id = $time->id;
$user->cars()->attach($id);
$user->reservations()->attach($R_id);
problem
the cars for rent is displaying in both tables because in the function I pulled all the cars.
Question
how can I get only the cars with reservation in one table(third table)? Without displaying them in the second table
First of all, you didn't design your car_user pivot table properly. You are storing the relationship for User and Car in that table but you are storing both types of relationship data using same properties, for sell and rent and there's no way to distinguish the difference as which one is for sell and which one is for rent. So, at first, you've to make a difference between both types of relationships using another field in that pivot table, so let's add another field in the table which will allow you to find out the relationship type, for example:
Table car_user:
user_id | car_id | type
------------------------
1 | 1 | buy
1 | 2 | rent
Here, the type will be used to identify the type of the relationship whether it's a rent or sell. So, when you attaching the relationship, add the type field (rent/buy) but before that, you've to make the relationship for them. So, you may use two separate relationship methods in User model, for example:
// For Rent
public function rentingCars()
{
return $this->belongsToMany(Car::class)
->wherePivot('type', 'rent')
->withPivot('type');
}
// For Buy
public function buyingCars()
{
return $this->belongsToMany(Car::class)
->wherePivot('type', 'buy')
->withPivot('type');
}
// For both types
public function buyingCars()
{
return $this->belongsToMany(Car::class)->withPivot('type');
}
Now, you can query for certain types of car using something like this:
public function show($id)
{
// Load all cars the user wants to buy
$users = User::with('buyingCars')->where( 'id', $id)->get();
// Notice "withUsers" not "withusers" (you've used "withusers")
// Or: view('show')->with('users', $users);
return view('show')->withUsers($users);
// More examples:
// Load all cars the user wants to rent
// $users = User::with('rentingCars')->where( 'id', $id)->get();
// Load all cars the user wants to buy or sell
// $users = User::with('cars')->where( 'id', $id)->get();
}
Now, when you attaching the cars to User model, you have to pass the value for the type field as well:
// For rent
$user->cars()->attach($car_id, ['type' => 'rent']);
// For buy
$user->cars()->attach($car_id, ['type' => 'buy']);
Also, when you do something like this:
$user = User::with('cars')->find(1);
You can check wheather a car is for rent or buy using something like this:
#foreach($user->cars as $car)
{{ $car->name }}
// Either buy or rent
{{ $car->pivot->type }}
#endforeach

laravel fill selectbox with foreign key

There are 3 tables
Sizes
id
name
Products
id
name
Product_sizes
id
product_id
size_id
I want to fill an selectbox with the id of product_sizes and the name of the foreign key connected table size.
for exampe:
product_sizes.id 1
sizes.name medium
where medium would be found by size_id in product sizes.
How can I the name value in the list?
What i currently have
I can get the right row with
$sizes = $product->sizeAvailable()->lists('pr', 'size_id');
where sizeAvailable is a relation that returns all product_sizes for a selected product.
First of all you don't need an id field in the pivot table because you can uniquely identify each row with the composite key product_id, size_id. A Product can belong to many Sizes and a Size can belong to many Products, thus you shouldn't have duplicate rows.
The relationships of each model are like the following:
class Product extends Model {
public function sizeAvailable() {
return $this->belongToMany('Size', 'product_sizes');
}
}
class Size extends Model {
public function products() {
return $this->belongToMany('Product', 'product_sizes');
}
}
Finally in your View you can use Blade functions to generate your selectbox:
<select>
#foreach($product->sizeAvailable() as $size)
<option value="{{ $size->id }}">{{ $size->name }}</option>
#endforeach
</select>

Categories