I am stuck on updating a eagerloaded model that has a "hasMany" relation.
I have one model like so:
class UserGroup extends Model
{
public function enhancements()
{
return $this->hasMany('App\UserGroupEnhancement');
}
}
My controller is passing $userGroup to the view like so:
$userGroup = $this->userGroup->with('enhancements')->whereId($id)->first();
and then in my view I have
#foreach($userGroup->enhancements as $enhancement)
<label>{{$enhancement->type}}</label>
<input class="form-control" name="enhancements[{{$enhancement->id}}][price]" value="{{$enhancement->price}}">
#endforeach
When updating, how do I update all of records in the enhancement relationship? It's passed back into multiple arrays. I am currently doing something like this.
public function update($id)
{
$userGroup = $this->userGroup->findOrFail($id);
$enhancement = \Input::get('enhancements');
if (is_array($enhancement)) {
foreach ($enhancement as $enhancements_id => $enhancements_price) {
$userGroup->enhancements()->whereId($enhancements_id)->update($enhancements_price);
}
}
}
Is there a way I can do this without needing the foreach loop? I see the push() method, but seems to only work on a single array.
There isn't a better way to do this. There is an Eloquent method called saveMany but it is used to create new records and not update. ExampleDoc:
$comments = [
new Comment(['message' => 'A new comment.']),
new Comment(['message' => 'Another comment.']),
new Comment(['message' => 'The latest comment.'])
];
$post = Post::find(1);
$post->comments()->saveMany($comments);
I would stick with your solution, you can even create a trait or a base Eloquent class and put that logic in a method so it can be used by all other models, if you ever need to.
Something like:
trait UpdateMany {
public function updateMany($updates, $relationshipName)
{
if (!empty($updates)) {
foreach ($updates as $update_id => $update) {
$this->{$relationshipName}()->whereId($update_id)->update($update);
}
}
}
}
Then attach to your model(s):
class UserGroup extends Model
{
use UpdateMany;
public function enhancements()
{
return $this->hasMany('App\UserGroupEnhancement');
}
}
And simply use as:
$userGroup = $this->userGroup->findOrFail($id);
$userGroup->updateMany(\Input::get('enhancements'), 'enhancements');
Related
I've two tables to save data to. One of them has foreign key so that I have one-to-many relationship. However, I don't understand how to save data into two table simultaneously. I have one query which contains data for one table and for another that should be attached to first one.
That is the main model
class Site extends Model
{
protected $fillable = ['path', 'site_link'];
public $timestamps = false;
public function features() {
return $this->hasMany('App\SiteFeature');
}
}
And this is the sub-model
class SiteFeature extends Model
{
protected $fillable = ['feature', 'site_id'];
public $timestamps = false;
}
Right now my controller looks like this
class SiteController extends BaseController
{
public function index()
{
return Site::all();
}
public function show(Site $id)
{
return $this->response->item($id, new SiteTransformer);
}
public function store(Request $request)
{
$site = Site::create($request->all());
return response()->json($site, 201);
}
I know that it would save it as one piece of data. And I ask you for help me to split data into two tables. In docs I've found the way to store with relationship to an existing model in DB, however I don't have that model at the moment of creation.
Solved that way
public function store(Request $request)
{
$site = Site::create([
"path" => $request->path,
"site_link" => $request->link,
]);
foreach ($request->features as $feature) {
$site->features()->save(new SiteFeature(["feature" => $feature]));
}
return response()->json($site, 201);
}
There are certain things you have to make sure of.
First: In your SiteFeature-Model the inverse relation to the Site-Models seems to be missing.
There should be a function like:
public function site()
{
return $this->belongsTo('App\Site');
}
See Laravel 5.6 - Eloquent Relationships, One-to-Many for this.
If however you have a relationship where (n) Sites can be related to (n) SiteFeatures, your relations and inverse relations have to be different.
(And there will also have to be a pivot table, in which you can store the n-to-n relation)
See Laravel 5.6 - Eloquent Relationships, Many-to-Many in that case.
Since your Question does not describe what is received with $request, here's what you should consider:
Validate your inputs. This will make sure you don't save garbage to your database
Check if you already have some part of the data-set you want to save, then save in two steps:
First step:
$site = Site::firstOrCreate(['path' => $request['input_name_for_path'],
'site_link' => $request['input_name_for_site_link'],
]);
This will give you a proper Site-Model saved to the database.
(Note, that this shows how you manually assign values to the fillable fields defined in the model in case you have different input field names)
Now you can go on an save the SiteFeature-Model connected to it:
$feature = SiteFeature::firstOrCreate('feature' => $request['input_name_for_feature');
$site->features()->attach($feature->id);
This should do the trick saving both, a new (or old) Site and a related SiteFeature to your database.
If I misunderstood the question, feel free to add information and I will update.
It's the correct way to save data using hasMany relationship without creating a new object of lookup model.
// inside controller
public function store(Request $request)
{
$student = Student::create([
"name" => $request->get('name'),
"email" => $request->get('email'),
]);
foreach ($request->subjects as $subject) {
$student->subjects()->create(["title" => $subject['title']);
}
return response()->json($student, 201);
}
// inside User model
public function subjects()
{
return $this->hasMany('App\Models\Subject');
}
I am new to Laravel. I am trying to use Eloquent Model to access data in DB.
I have tables that shares similarities such as table name.
So I want to use one Model to access several tables in DB like below but without luck.
Is there any way to set table name dynamically?
Any suggestion or advice would be appreciated. Thank you in advance.
Model:
class ProductLog extends Model
{
public $timestamps = false;
public function __construct($type = null) {
parent::__construct();
$this->setTable($type);
}
}
Controller:
public function index($type, $id) {
$productLog = new ProductLog($type);
$contents = $productLog::all();
return response($contents, 200);
}
Solution For those who suffer from same problem:
I was able to change table name by the way #Mahdi Younesi suggested.
And I was able to add where conditions by like below
$productLog = new ProductLog;
$productLog->setTable('LogEmail');
$logInstance = $productLog->where('origin_id', $carrier_id)
->where('origin_type', 2);
The following trait allows for passing on the table name during hydration.
trait BindsDynamically
{
protected $connection = null;
protected $table = null;
public function bind(string $connection, string $table)
{
$this->setConnection($connection);
$this->setTable($table);
}
public function newInstance($attributes = [], $exists = false)
{
// Overridden in order to allow for late table binding.
$model = parent::newInstance($attributes, $exists);
$model->setTable($this->table);
return $model;
}
}
Here is how to use it:
class ProductLog extends Model
{
use BindsDynamically;
}
Call the method on instance like this:
public function index()
{
$productLog = new ProductLog;
$productLog->setTable('anotherTableName');
$productLog->get(); // select * from anotherTableName
$productLog->myTestProp = 'test';
$productLog->save(); // now saves into anotherTableName
}
I created a package for this: Laravel Dynamic Model
Feel free to use it:
https://github.com/laracraft-tech/laravel-dynamic-model
This basically allows you to do something like this:
$foo = App::make(DynamicModel::class, ['table_name' => 'foo']);
$foo->create([
'col1' => 'asdf',
'col2' => 123
]);
$faz = App::make(DynamicModel::class, ['table_name' => 'faz']);
$faz->create([...]);
I am using Laravel 5.2 and using a polymorphic relations table for a feeds page. A feed has pictures, articles, and links that have their own respective models. The controller method that I am using for the feed looks like this:
public function index()
{
$allActivity = Activity::get();
$activity = collect();
foreach($allActivity as $act)
{
$modelString = $act->actable_type;
$class = new $modelString();
$model = $class->find($act->actable_id);
$activity->push($model);
}
return view('feed', compact('activity'));
}
and here is the feed.blade.php view
#foreach($activity as $class)
// Gives me the model name so the correct partial view could be referenced
<?php
$split = explode("\\", get_class($class));
$model = lcfirst($split[1]);
?>
#include("partials.{$model}", [$model => $class])
#endforeach
Because of this setup, I can't get pagination using the method outlined in the Laravel documentation. How could I correctly implement pagination using this setup? Any help would be greatly appreciated.
Access your relation using the actable() relation you should have on your Activity model. It will also help you avoid using find() in the loop like you are which will give you an N+1 issue.
In your activity model you should have an actable method:
class Activity
{
public function actable()
{
return $this->morphTo();
}
}
Then in your view you can lazy load all polymorphic actable relations and pass to the view. You can even keep your view clean and resolve the model name in the map() function:
public function index()
{
$activity = Activity::with('actable')->get()->map(function($activity) {
$activity->actable->className = lcfirst(class_basename($activity->actable));
return $activity->actable;
});
return view('feed', compact('activity'));
}
Then in your view:
#foreach($activity as $model)
#include("partials.{$model->className}", [$model->className => $class])
#endforeach
To run this with pagination it would be:
Controller:
public function index()
{
$activities = Activity::with('actable')->paginate(25);
return view('feed', compact('activities'));
}
View:
#foreach($activities as $activity)
#include('partials.'.lcfirst(class_basename($activity->actable)), [lcfirst(class_basename($activity->actable)) => $activity])
#endforeach
I'm performing validation of a form, where a user may select a range of values (based on a set of entries in a model)
E.g. I have the Model CfgLocale(id, name)
I would like to have something like:
CfgLocale->listofAvailableIds() : return a array
What I did is:
Inside Model this method:
class CfgLocale extends Model
{
protected $table = 'cfg_locales';
public static function availableid()
{
$id_list = [];
$res = self::select('id')->get();
foreach($res as $i){
$id_list[] = $i->id;
}
return $id_list;
}
}
On Controller for validation I would do then:
$this->validate($request, [
'id' => 'required|integer|min:1',
...
'locale' => 'required|in:'.implode(',', CfgLocale::availableid()),
]);
Any better Idea, or Laravel standard to have this done?
Thanks
You can use exists rule of laravel.You can define a validation rule as below. Might be this can help.
'locale' => 'exists:cfg_locales,id'
Use this code instead,
class CfgLocale extends Model
{
protected $table = 'cfg_locales';
public static function availableid()
{
return $this->pluck('id')->toArray();
}
}
pluck method selects the id column from your table and toArray method converts your model object collection into array.
Know more about Laravel Collections here.
This will return an array of IDs:
public static function availableid()
{
return $this->pluck('id')->toArray();
}
https://laravel.com/docs/5.3/collections#method-pluck
https://laravel.com/docs/5.3/collections#method-toarray
I have a question about laravel model relations and use them in eloquent class . my question is this :
I have a model like this :
class TransferFormsContent extends Model
{
public function transferForm()
{
return $this->belongsTo('App\TransfersForms','form_id');
}
}
and in transferForm i have other side for this relation like this :
public function transferFormsContent()
{
return $this->hasMany('App\TransferFormsContent', 'form_id', 'id');
}
also in transferForm i have another relation with employee like this :
class TransfersForms extends Model
{
public function employee()
{
return $this->belongsTo('App\User','employee_id');
}
}
now if I want get a record from "TransferFormsContent" with its "transferForm " provided its with employee. how can i do this?
i now if i want get "TransferFormsContent" with only "transferForm " i can use from this :
$row = $this->model
->with('transferForm');
but how about if i want transferForm also be with its employee?
ok i find that:
only you can do that with this :
$row = $this->model
->with('transferForm.employee')
now you have a record from "TransferFormsContent" with its "transferForm " provided its with employee.
You can use nested eager loading with dot notation:
$row = $this->model
->with('transferForm.employee');
Or you can use closure:
$row->$this->model
->with(['transferForm' => function($q) {
$q->with('employee')
}]);
Second method is useful when you need to sort or filter by employee