Controller and Eloquent woes - laravel

I am new to Laravel and have been banging my head on this issue for a while. I am merely trying to get a single row from a table and hand it off to a view.
The table has two fields that should match up with this query, the first of course is the id and the second is user_id which matches the logged in user. When its done I plan on responding with a failure message (no record found that matches id: X).
public function show($id)
{
$data = Partners::where('id', $id);->where('user_id', Auth::user()->id)->get();
return View::make('partners.showone')
->with('data', $data)
->with('title', 'View Record')
->with('breadcrumb', 'View Partner');
}
In my view:
{{ $data->firstName }}
This configuration gives me an error of:
Undefined property: Illuminate\Database\Eloquent\Builder::$firstName

Typo...you have a ; in the middle there....it should be....
$data = Partners::where('id', $id)->where('user_id', Auth::user()->id)->get();
but your query really should be this..
$data = Partners::find($id)->where('user_id', Auth::user()->id)->first();
if you just want one row
EDIT (based on your comments below)
For your phones in your Partner model (Im working with Laravel 3 btw)
function phone(){
return $this->hasMany('Phone');
}
Then with the above $data query, you can get the phone by...
$data->phone();

Related

How to get user multiple column in Laravel Relationship?

I am using Laravel 9, I stuck into the Relationship, I have a table called test_series_question another is test_series_responses. Every test_series_question has one row in test_series_responses. I need to select the responses available in the table. Something like WHERE question_id = '$id' AND test_id = $test_id
I have tried to to get the responses from Laravel Model
function response()
{
return $this->hasOne(TestSeriesResponse::class, 'question_id', 'id');
}
It's working fine, But There is a one column named test_id and if I dont compare test_id It'll return previously submitted responses which match the question_id id not the test_id
I have two questions
Can I put a parameter into function response() in Model from controller?
How can I achive the thing, Please help me out.
Here is the Controller code:
function testOngoing($test_id, $history_id)
{
$test = TestSeries::find($test_id);
$history = $history_id;
$questions = TestSeriesQuestion::where('test_id', $test_id)->with('response')->paginate(1);
$data = compact('test', 'questions', 'history');
return view('test-series/test-question')->with($data);
}
Maybe something like
$questions = TestSeriesQuestion::with(['response' => function ($query) use ($history_id) {
$query->where('history_id', $history_id);
}])->where('test_id', $test_id)->paginate(1)

Looking up model in Laravel after returning array of objects in Controller

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'));
}

Laravel - Filter records by distinct relation

Right now I have the following models structure,
Country -> State -> City -> Student
And the Student model includes first_name and last_name.
So, I want countries to by filtered by giving student's first name. Like if I give John then I want list of countries which has students whose first name is John.
I was trying something like this,
I added a method called Students() in Country model and returning Student instances from that method. But now I stuck to find out how to filter countries.
Thanks in anticipation.
I came across a similar question recently and I came with the following solution myself. Probably, there are easier ways, but this will get you going for now, I guess.
First we query all the users with first_name == John, as you described, and we limit the query to output only the ID's.
$users = User::where('first_name', 'John')->get()->pluck('id');
We then cross-compare this with the result of Students() from the country model. As I don't know what you're querying for to get the country that you want, I'll just take the Netherlands as an example — that's where I'm from.
$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();
For this to work, you must make sure that within the Students()-function in your model, the get() is left out.
Final 'result':
$users = User::where('first_name', 'John')->get()->pluck('id');
$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();
in the Student Model create this:
public function city()
{
return $this->belongsTo(City::class,'city_id', 'id');
}
and in the City Model create this:
public function state()
{
return $this->belongsTo(State::class,'state_id', 'id');
}
Finally in the State Model:
public function country()
{
return $this->belongsTo(Country::class,'country_id', 'id');
}
For example if you made things like that in controller:
$students = Student::where('name', 'John')->get();
in the view:
#foreach($students as $student)
$student->city->state->country->country_name;
#endforeach
You can access like that.
If you have setup the model and relationship properly then you need to call them using in with function
$students = Student::where('name','John')->with('city.state.country')->get();
Loop through the $students
#foreach($students as $student)
{{ $student->city->state->country }}
#endif

Distinct pivot results with Eloquent

Inside my Laravel project, I'm printing out all the business cards of my contacts.
In the contact model I have:
public function organizations()
{
return $this->belongsToMany('Organization')->withPivot('ContractStatus')->withTimestamps();
}
So in that way, I can show all the companies the contact is still working for.
In the footer of my contacts overview page, I want to print out all the associated companies logo's for that particular search query.
But something like this:
#foreach($contacts as $key => $value)
#foreach($value->organizations as $organization)
#endforeach
#endforeach
Will print duplicated company logo's as soon as the search results contains 2 contacts that both work for the same company.
If you want to list a distinct collection of a collection of contacts, then don't use relation, but whereHas:
$contactsIds = $contacts->modelKeys();
$organizations = Organization::whereHas('contacts', function ($q) use ($contactsIds) {
$q->whereIn('contacts.id', $contactsIds);
})->get();
Another way would be this trick, in case you in fact need to load the relation:
$organizations = null;
$contacts = Contact::with(['organizations' => function ($q) use (&$organizations) {
$organizations = $q->get();
}])->get();
$organizations = $organizations->unique();
This will load the relation as usually and also run additional query and assign its result to $organizations.
In the controller action generate a new Collection with the organizations:
$uniqueOrganizations = new Collection();
foreach($contacts as $contact)
$uniqueOrganizations->merge($contact->organizations);
Then pass it to the view, to show all the different organizations
#foreach($uniqueOrganizations as $org)
//show org logo
#endforeach

Pass data from view to controler

I am making a laravel app and I want to pass data to the controller from a view. I want to pass the id of a vehicle in order to get certain information for that car from another table.
desc.blade.php
{{link_to_action('Insur_DocController#index', "Insurances&Docs", $v->id, array('id'=>$v->id))}}
Insur_DocController#index
public function index()
{
$values = DB::select('select * from insur_docs where car_id=?', $id);
return View::make('pages.insur_docs', array(
'values' => $values,
));
}
Displays this error: Undefined variable: id
Assuming that you have a route:
Route::get('car/{id}', 'Insur_DocController#index');
Your controller method must expect the $id:
public function index($id)
{
...
}
Your select will not work this way, you could change it to:
$values = DB::table('insur_docs')->where('car_id', $id)->get();
And check if you got something:
dd($values);
This line of code will dump and die your script, so you can see the result of your query.
There is also an error in the link, which should be:
{{link_to_action('Insur_DocController#index', "Insurances&Docs", array('id'=>$v->id))}}

Resources