Im replicating a trips table. On the trips form, there is a dropdown to select species. A user can select many species to. Im having trouble replicating this species table beacuse its in its own table, and its a collection. So using "replicate" wont work.
This is how Im replicating the trips table right now:
public function replicateTrip (Request $request, $slug, $id) {
$listing = $request->user()->listings()->where('slug', $slug)->first();
$trip = $listing->trips()->where('id', $id)->first();
$replicateTrip = Trip::find($trip->id);
// This is how im getting the species from the species table
$replicateSpecies = DB::table('species_trip')->where('trip_id', $id)->get();
$newTask = $replicateTrip->replicate();
$newTask->save();
return redirect()->back();
}
If I DD the $replicateSpecies variable when cloning my current trip, I get:
I need to replicate the species array from my orginal trip into the species table, and I cant just use "replicate", because its a collection.
So my question is how would I replicate this collection? Or if there is another method of doing this?
You can try it as:
public function replicateTrip (Request $request, $slug, $id) {
$listing = $request->user()->listings()->where('slug', $slug)->first();
$trip = $listing->trips()->where('id', $id)->first();
$replicateTrip = Trip::find($trip->id);
// This is how im getting the species from the species table
$replicateSpecies = DB::table('species_trip')->where('trip_id', $id)->get();
$newTask = $replicateTrip->replicate();
$newTask->save();
$replicateSpecies->each(function ($item, $key) use($newTask) {
$copy = $item->replicate();
$copy->trip_id = $newTask->id;
$copy->save();
})
return redirect()->back();
}
Related
I have a table that houses hotel ids and amenity ids. When a user chooses amenities i need to only pull hotels that have ALL of the chosen amenities. As of now it gets me all hotels that have at least one. How can i change this builder query to handle it so it does not include hotels that do not have all of them.
$builder = Hotels::query();
$builder->select('hotels.id','hotels'.'hotels_name')
$request_amenities = $request->amenities;
$builder->join('amenities_hotels', function ($join) use($request_amenities) {
$join->on('amenities_hotels.hotel_id', '=', 'hotel.id')
->whereIn('amenities_hotels.amenities_id', $request_amenities);
});
It's something like WhereAll you need ...
you have to add whereHas, for every Item in your array.
$builder = Hotels::query();
$builder->select('hotels.id', 'hotels' . 'hotels_name');
$request_amenities = $request->amenities;
if($request_amenities!=null)
{
for ($i = 0; $i < $this->count($request_amenities); $i++) {
$builder = $builder->whereHas('amenitiesHotels', function ($query) use ($i, $request_amenities) {
$query->where('amenities_hotels.amenities_id', $request_amenities[$i]);
});
}
see more about where in all in this question
Hotels model.
// ...
public function amenities(): BelongsToMany
{
return $this->belongsToMany(
Amenities::class,
"amenities_hotels"
);
}
// ...
Query to run.
Hotels::select(['hotels.id','hotels'.'hotels_name'])
->whereHas('amenities', function ($query, $request_amenities) {
$query->whereIn('amenities.id', $request_amenities);
}, '=', count($request_amenities))->get();
The above query tells Laravel to load the hotels that have count($request_amenities) amenities relation records when the amenities relation records are filtered by the given array of IDs.
Resource: "Where Has All" Functionality in Laravel
I define the relation in Company table (where I added the plural):
protected $table = 'companies';
public function country() {
return $this->belongsTo(Country::class, "country_id")->withDefault(['country' => 'unknown']);
}
I also did the same in the Country model.
When I use the following code in the controller show function it works:
public function show (Company $company) {
$company->country = $company->country()->pluck('country');
But if I use the same code in the index function in a loop, I get an error "Call to undefined method stdClass::country()":
public function index (Company $company) {
if (request('tag')) {
$companies = Tag::where('name',request('tag'))->firstOrFail()->companies;
$companies->page_title = "Businesses matching tag '".request('tag')."'";
} else {
$companies = DB::table('companies')
->where([['is_active', '=', '1']])
->orderBy('company')
->get();
}
foreach($companies as $key => $thisCompany) {
...
$thisCompany->country = $company->country()->pluck('country');
}
I guess it is due to the fact that $company is created in the loop and not passed through the function like in show(Company $company)... but I could not find how to solve this issue... so help will be appreciated.
I have added the model in the argument of the function and change the name of the $company variable in the loop by $thisCompany to avoid confusion with the $company model.
No error but the field $country->country does not contain the name of the country but "Illuminate\Support\Collection {#443 …1}"
Why is it so complicated? Please help...
Paul, sorry, I think I didn't explain myself well in the comments.
What I meant by "What about if you change DB::table('companies') by Company?", is to stop using DB Query Builder to use the Eloquent Company model.
Specifically in this segment of code:
$companies = DB::table('companies')
->where([['is_active', '=', '1']])
->orderBy('company')
->get();
So, it could be:
$companies = Company::where([['is_active', '=', '1']])
->orderBy('company')
->get();
The explanation is that in the first way (with DB Query Builder), the query will return a collection of generic objects (the PHP stdClass object) that do not know anything about the Company and its relationships.
On the other hand, if you use the Eloquent model Company, it will return a collection of Company objects, which do know about relationships, and specifically the relationship that you have defined as country.
Then, when you loop over the collection, you will be able to access the country relation of each Company object:
foreach($companies as $key => $company) {
//...
$company->country = $company->country()->pluck('country');
}
Finally, your code could looks like:
public function index () {
if (request('tag')) {
$companies = Tag::where('name',request('tag'))->firstOrFail()->companies;
$companies->page_title = "Businesses matching tag '".request('tag')."'";
} else {
$companies = Company::where([['is_active', '=', '1']])
->orderBy('company')
->get();
}
foreach($companies as $key => $company) {
//...
$company->country = $company->country()->pluck('country');
}
//...
}
I am trying to do something I've never done before in Laravel and cannot figure out how to do it.
I have the following code in my Controller:
public function show($id)
{
//Get application for drug
$application = PharmaApplication::where('ApplNo', $id)->first();
//Get all products for given application (i.e. the different quantities and forms drug comes in)
$product = PharmaProduct::where('ApplNo', $id)->get();
foreach($product as $product){
$product->ProductNo;
}
//Get Marketing Status for drug
$marketingStatus = DB::table('pharma_marketing_statuses')
->where('ApplNo', $id)
->where('ProductNo', $product->ProductNo)
->get();
//Lookup marketing status Description
$marketingStatusDescription = PharmaMarketingSatusLookup::where('MarketingStatusID', $marketingStatus->MarketingStatusID);
return view('profiles.drug', compact('application', 'product', 'marketingStatus', 'marketingStatusDescription'));
}
I am trying to accomplish the following:
Get the application for a drug - this part of my code works
Return an array of objects for the products (i.e. 7 products that belong to one application). I can do this but get stuck going to the next part.
Next, I have to use the array of objects and search a table with the following columns: MarketingStatusID, ApplNo, ProductNo. I know how to query this table and get one row, but the problem is I have an array that I need to search. I imagine I have to use a loop but don't know where.
Finally, I use the MarketingStatusID to retrieve the MarketingStatusDescription which I will know how to do.
I am also getting an error message that says:
Class 'App\Http\Controllers\profiles\PharmaMarketingSatusLookup' not found
In my Controller, I have use App\PharmaMarketingStatusLookup; so I am not sure why it is searching the Controllers folder
You have a typo in your class
From PharmaMarketingSatusLookup change to PharmaMarketingStatusLookup
App\Http\Controllers\profiles\PharmaMarketingStatusLookup
USE whereIn
use App\PharmaApplication;
use App\PharmaProduct;
use App\PharmaMarketingSatusLookup;
public function show($id)
{
$application = PharmaApplication::where('ApplNo', $id)->first();
$products = PharmaProduct::where('ApplNo', $id)->get();
$productid = array();
foreach($products as $product){
$productid[] = $product->ProductNo;
}
$marketingStatus = DB::table('pharma_marketing_statuses')
->where('ApplNo', $id)
->whereIn('ProductNo', $productid)
->get();
$marketingStatusDescription = PharmaMarketingSatusLookup::where('MarketingStatusID', $marketingStatus->MarketingStatusID);
return view('profiles.drug', compact('application', 'product', 'marketingStatus', 'marketingStatusDescription'));
}
Is it possible to get data from the model in a function? I want to get the SupplierID data from the Product model.
public function productAjax($id)
{
$product = new Producttext();
$products = $product->productexts($id);
$hitung_products = $products->count();
$suplierproduct = Company::select('id', 'CompanyName')
->where(['id' => $products->SupplierID])
->first();
}
However, on execution, I get the following error.
Property [SupplierID] does not exist on this collection instance.
If you have producttext ID then
$product = Producttext::find($id)
OR
$product = Producttext::where('id',$id)->first();
//test and check that you have it $product->SupplierID
$suplierproduct = Company::select('id', 'CompanyName')->where('id',$product->SupplierID)
->first();
You should try this:
public function productajax($id)
{
$products = Producttext::where('id',$id)->first();
$suplierproduct = Company::select('id', 'CompanyName')
->where(['id' => $products->SupplierID])
->first();
}
This is sort of a tricky question. Ill try to explain it as best as I can. I have a trip, and I want users to click a copy button on that trip, which will just replicate that trip again, so users don't have to fill out a huge form again.
The trip form saves to 4 models (tables).
This is how Im doing the replicating right now:
public function replicateTrip (Request $request, $slug, $id) {
$listing = $request->user()->listings()->where('slug', $slug)->first();
$trip = $listing->trips()->where('id', $id)->first();
$replicateTrip = Trip::find($trip->id);
$replicatebringToTrip = BringToTrip::where('trip_id', $id)->first();
$replicateIncludedInPriceForTrip = IncludedPriceTrip::where('trip_id', $id)->first();
$replicateNotIncludedInPriceForTrip = NotIncludedPriceTrip::where('trip_id', $id)->first();
$newTask = $replicateTrip->replicate();
$newTask2 = $replicatebringToTrip->replicate();
$newTask3 = $replicateIncludedInPriceForTrip->replicate();
$newTask4 = $replicateNotIncludedInPriceForTrip->replicate();
$newTask->save();
$newTask2->save();
$newTask3->save();
$newTask4->save();
return redirect()->back();
}
So this is how a replicated trip looks like on the main trips table:
Then I got 3 other diffrent models (tables) which it saves data to from that trip ID.
So for example here is my other table that the data is replicated to:
As you can see, the data replicated succesfully, BUT, the "trip_id" column, which in this case is 1259 is still the same as the original trip I replicated. I need to get the new replicated trip_id, and insert it into the other 3 models I have. So in this case, the second row would be 1262 NOT 1259.
You can try it as:
public function replicateTrip (Request $request, $slug, $id) {
$listing = $request->user()->listings()->where('slug', $slug)->first();
$trip = $listing->trips()->where('id', $id)->first();
$replicateTrip = Trip::find($trip->id);
$replicatebringToTrip = BringToTrip::where('trip_id', $id)->first();
$replicateIncludedInPriceForTrip = IncludedPriceTrip::where('trip_id', $id)->first();
$replicateNotIncludedInPriceForTrip = NotIncludedPriceTrip::where('trip_id', $id)->first();
$newTask = $replicateTrip->replicate();
$newTask2 = $replicatebringToTrip->replicate();
$newTask3 = $replicateIncludedInPriceForTrip->replicate();
$newTask4 = $replicateNotIncludedInPriceForTrip->replicate();
$newTask->save();
$newTask2->trip_id = $newTask->id;
$newTask3->trip_id = $newTask->id;
$newTask4->trip_id = $newTask->id;
$newTask2->save();
$newTask3->save();
$newTask4->save();
return redirect()->back();
}