I'd like to bind my checkbox group Form::checkbox('services[]') with data from my pivot table but I'm having trouble doing so, I think this is because no key is being returned with service_id.
My data model is as follows:
Business
Service
Business_Service table to store many to many link.
Blade Template
#foreach($service as $service)
{!! Form::checkbox('services[]', $service->id, (in_array($service->id, $selected_services) ? true : false)) !!}
#endforeach
Controller
$service = Service::all();
$selected_services = Auth::user()->business->services()->get();
return view('signup.step2', compact('service', 'selected_services'));
When I return $selected_services I can see the following:
[{"id":2,"name":"Service
1","image":"picture.png","created_at":"2017-03-31
00:31:20","updated_at":"2017-03-31
00:31:20","pivot":{"business_id":103,"service_id":2}},{"id":3,"name":"Service
2","image":"picture.png","created_at":"2017-03-31
00:31:23","updated_at":"2017-03-31
00:31:23","pivot":{"business_id":103,"service_id":3}}]
I have tried changing $selected_services like this:
$selected_services = Auth::user()->business->services()->keyBy('service_id');
But this only returns one row and doesn't associate a key to the row as expected.
If you want to use inbuilt Laravel functions, then you could use the Collection::pluck function.
$businessServices = Auth::user()->business->services->pluck('id');
I can prepare another array instead of using the collection Eloquent returns but I was hoping there was some built-in function by Laravel I could use.
$service = Service::all();
$business_services = Auth::user()->business->services()->get();
$selected_services = [];
foreach ($business_services as $ss) {
$selected_services[] = $ss->pivot->service_id;
}
return view('signup.step2', compact('service', 'selected_services'));
Related
I have a hasOne(Many) relation function like this:
return $this->hasOne('App\Models\ProductTranslation','product_id','id')->where('language_id', $language_id['id']);
Also, I tried to use
return $this->hasOne('App\Models\ProductTranslation','product_id','id')->select('product_translations.name')->where('language_id', '1');
In Controller use this
$value=Product::with('translation:name')->find(1);
I try to receive only one specific column from the table, but it returned an empty array. In debug bar I see the query when I use it in PHPMyAdmin it return only one column as I want.
Is this possible?
P.S (use Laravel 5.8.34)
Updating
I choose 'Entity Layers for Translated Fields and Non-Translated Fields' approach for translation in the project and have a database like this Database picture
If you want to get only that language_id type of translation then you might do like this.
$language_id = 1;
$products = Product::with(array('translation'=>function($query) use($language_id){
$query->where('language_id',$language_id);
}))->get();
and if you want to select name then like this
make sure you've to select id,name id is a must.
$language_id = 1;
$products = Product::with(array('translation'=>function($query) use($language_id){
$query->where('language_id',$language_id)->select('id','name');
}))->get();
Remove where conditions from models.
As per your DB structure in Language it's belongsToMany with role
Languages.php model
public function role(){
returh $this->belongsToMany('App\Models\Role','role_translations','language_id','role_id')
}
$language_id = 1;
$products = Product::with(array('translation.role'=>function($query) use($language_id){
$query->where('role_translations.language_id',$language_id)->select('languages.id','languages.name');
}))->get();
Suppose I have a query that, among other things, returns user id's, this query was built using DB::table()... rather than using the models, so, as a result, I got a collection with arrays for each retrieved row, something like this:
user_id | calculated_data
--------+----------------
1 | 123
2 | 111
3 | 222
... | ...
Supose I store this collection on a $data variable, of course if I do a foreach ($data as $d) { $d->user_id ... } will work.
But I want this query to return something more like what the ORM does, so instead user_ids, return User models so I can do, for example, a $data->user->name
Can this be even done? if so, how?
You can use the hydrate() function, it accepts an array of stdClass objects (or even associative arrays AFAIR) as input and returns a collection of Eloquent Models, so you can do things like this:
$result = DB::table('users')->take(10)->get();
$users = App\User::hydrate($result->all());
You can even get a collection of Eloquent Models directly from a RAW query with the fromQuery() function, i.e.:
$users = App\User::fromQuery('SELECT * FROM users WHERE id > ?', [2])
Update: If in your collection you don't have all the fields to hydrate a model, you can preload all the users you need with one query and modify your collection, i.e.:
$users = App\User::find($data->pluck('user_id'));
$data->transform(function($item) use($users) {
$item->user = $users->where('id', $item->user_id)->first()
return $item;
});
You need to use Eloquent to call value the "ORM way" I did not find anything related to the query builder in relation to ORM.
You could do something like this:
$flights = App\Flight::all();
foreach ($flights as $flight) {
echo $flight->name;
}
And in the ORM way you would get the user like this:
foreach ($flights as $flight) {
echo $flight->user->name;
}
Of course you would need to setup the correct relations.
// initial query will return collection of objects
$query = DB::table('user_something')
->join('users', 'users.id', 'user_something.user_id');
// You could cast it to the model query, by using fromSub.
// Make sure to alias a subquery same as the model's name,
// otherwise it would not be able to parse models data
User::fromSub($query, 'users');
// The most robust way is to get table name from the model
User::fromSub($query, User::make()->getTable());
i am using laravel 5.1 and want to retrieve a single row in the database then manipulate it after.
my current code is
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
foreach($profiles as $profile ){
$data['address'] = $profile->address;
}
why cant i do it like this?
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
$data['address'] = $profiles->address;
am i using a wrong function or something?
thanks in advance.
Try this:
$data['address'] = $profiles[0]->address;
When you are using get(), it returns an array of Std class object.
In addition to retrieving all of the records for a given table, you may also retrieve single records using first. Instead of returning a collection of models, these methods return a single model instance:
// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)->first();
laravel 5.8
Retrieving A Single Row / Column From Profile
If you just need to retrieve a single row from the database table, you may use the first() method. This method will return a single stdClass object:
$Profile = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->first();
If you don't even need an entire row, you may extract a single value from a record using the value() method. This method will return the value of the column directly:
$address = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->value('address');
From the laravel docs we know that we can filter Eloquent collections after retrieval from database by applying a filter :
$users = $users->filter(function($user)
{
return $user->isAdmin();
});
Does anyone knows if we can filter the collections by a unique column/attribute that is not the primary key?
Edited: Say I have an column slug and I want to filter the collection based on distinct slug values , removing duplicates along the way.
I know this is old but you could try something like this:
$existingSlugs = [];
$users = $users->filter(function($user) use (&$existingSlugs)
{
$duplicate = in_array($user->slug, $existingSlugs);
if(!$duplicate) {
$existingSlugs[] = $user->slug;
}
return !$duplicate;
});
I want to find all patients that belong to a user where id = 1
This works:
$data = Patient::where('user_id', '=', 1)
->with('method', 'images')->get()->toJson();
This doesn't work:
$data = User::find(1)->patients->with('method', 'images')->get()->toJson();
It says:
Call to undefined method Illuminate\Database\Eloquent\Collection::with()
Why is it wrong? Could it be corrected?
The reason your code doesn't work is all Eloquent relationship declaration returns different result depending on whether you are trying to access the relationship as property or as method (with () or without ()).
// Return you chainable queries
$query = User::find(1)->patients()->...
// Return you collection of patients
$patientsCollection = User::find(1)->patients;
Try
User::find(1)->patients()->with('method', 'images')->get()->toJson();
Try this
$patient = New Patient;
$data = $patient->where('user_id','=',1)->with('method','images')->get()->toJson();