Attach to all possible relations from many-to-many method on create? - laravel

I have two Model named Position and Event, they have many-to-many relationship with each other.
Event:
<?php
class Event extends Model
{
protected $fillable = [
'name', 'opta_id'
];
public function positions() {
return $this->belongsToMany(Position::class);
}
}
Position:
class Position extends Model
{
protected $fillable = [
'name', 'short_name'
];
public function events() {
return $this->belongsToMany(Event::class);
}
}
Each event should have a pivot entry for each position currently in the database, there are no exceptions. So every time a user creates a new event, I want to create a pivot entry for each existing position.
I am struggling to figure this out using the documentation and SO. I could use sync() or attach() to make the connections by explicitly naming the IDs of all the positions in the db. In the EventController's store method:
$data = $request->all();
$event = Event::create($data);
$event->positions()->sync([1, 22, 34, 167]);
But for this to work, I would first have to get all the entries from the positions table, format them into an array of IDs, and pass them to this method. Is there any built-in or canonical way to do this?

There is no built-in way, but the manual solution is quite short:
$event->positions()->attach(Position::pluck('id'));
attach() is more efficient than sync() because it inserts all pivot records in a single query.

I've gotten the other solution, So to may achieve your purpose you have
// the 1st sync will remove all the relationship to the position table
$event->positions()->sync([1, 22, 34, 167]);
// the 2nd sync is to extend the relationship from the 1st
$event->positions()->syncWithoutDetaching([1, 22, 34, 167]);

Related

How to make shortest code?

I use the following code to insert multi array to database:
foreach($request->category as $k => $v){
$category[] = array(
"category_id" => $v,
"announcement_id" => $announcement->id
);
}
AnnouncementCategory::insert($category);
So, input data is POST array $request->category.
I need to refactoring this code
I tried this code:
$announcement->categories()->attach($request->category);
In model Announcement I have:
public function categories()
{
return $this->hasMany("App\AnnouncementCategory", "announcement_id", "id");
}
If you define in your Announcement model relationship like this:
public function categories()
{
return $this->belongsToMany(AnnouncementCategory::class);
}
you can do it like this:
$announcement->categories()->attach($request->category);
EDIT
I see you updated your question and added categories relationship. But looking at your code, AnnounceCategory is rather pivot table, so you should use belongsToMany as I showed instead of hasMany
You can do it in one line if the request matches the columns:
AnnouncementCategory::insert($request->all());
Then in your AnnouncementCategory model, make sure you declare the protected $fillable array where you specify which field could be populated.

Laravel 5: How to use firstOrNew with additional relationship fields

I have a CMS that allows the user to save and create bike tours. Each bike tour also has categories, which are definined using Laravel's Many to Many relationship utilising an intermediary pivot table. At the point of saving a tour, we don't know if the tour is an existing one being edited, or a new one.
I think I should be using Laravel's firstOrNew method for saving the tour, and the sync method for saving categories. However, all the tutorials very simplistically just give the example of passing a single object to the function like so:
$tour = Tour::firstOrNew($attributes);
But what happens when my $attributes also contains extra stuff, like the categories which are linked to a relationship table, and which I will need to save in the next step? For example this very good tutorial gives the following example:
$categories = [7, 12, 52, 77];
$tour = Tour::find(2);
$tour->categories()->sync($categories);
But what happens if the category data is bundled with the data for the rest of the tour, and instead of using find I need to use firstOrNew to create the tour? Should I keep the categories in the $attributes while I instantiate the tour, then run the sync, then unset them before saving the tour, or...? Is there a better way to achieve this?
EDIT: To be clear, the $attributes variable in my example here is essentially the tour object data bundled together- just as the Laravel/Eloquent system would return it from the transaction using the belongsToMany method- with subequent modifications from the user). ie: here is a snapshot of what it contains:
array (
'id' => 1,
'uid' => '03ecc797-f47e-493a-a85d-b5c3eb4b9247',
'active' => 1,
'code' => '2-0',
'title' => 'Tour Title',
'url_title' => 'tour_title',
'distance_from' => 20,
'distance_to' => 45,
'price_from' => '135.00',
'price_to' => '425.00',
'created_at' => '2013-12-31 15:23:19',
'updated_at' => '2015-07-24 16:02:50',
'cats' => // This is not a column name!
array (
0 => 1,
1 => 7
),
)
All of these attributes are column names in my tours table, other than cats, which references another table via a hasMany relationship. Do I need to unset it manually before I can set this object class and save it with $tour->save?
I am looking for the cleanest most Laravel way to do it?
EDIT2: Here is the relationship defined in the Tours model:
class Tour extends Model
{
protected $guarded = [];
public function cats(){
return $this->belongsToMany('App\TourCategory', 'tour_cat_assignments', 'tour_id', 'cat_id');
}
}
you need to define $fillable property of your Tour model to tell eloquent which attributes to consider when using mass assignment so it will ignore categories related attributes silently. for ex.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tour extends Model {
protected $fillable = ['name'] //... other attributes which are part of this model only and laravel will consider only these attributes and ignore category related attributes which you can consider later use.
}
You can use firstOrCreate. The data actually gets persisted using this method.
$categories = [7, 12, 52, 77];
$tour = Tour::firstOrCreate($attributes)->cats()->sync($categories);
Got to make sure the fields are mass-assignable to be able to use the firstOrCreate method though. So either set the fieldnames in the $fillable property or put this in the Tour model:
protected $guarded = [];
Since you have mentioned "CMS" and "subsequent modifications from user", I guess that you are getting your attributes from a Form which means you are getting a Request object/collection.
If that is the case then you can try
$tour = Tour::firstOrCreate($request->except('cats'));
$categories = [];
foreach($request->get('cats') as $key=>$value){
$categories[] = $value;
}
$tour->cats()->sync($categories);
However, if your $attributes us constructed as an array (probably with some manipulations on form data) as per your EDIT then in that case you may try:
$tour = Tour::firstOrCreate(array_except($attributes, ['cats']);
$categories = [];
foreach($attributes['cats'] as $key=>$value){
$categories[] = $value;
}
$tour->cats()->sync($categories);
In any case, you must have the mass assignable fields declared in $fillable property in your model i.e. Tour.
Hope this helps.

Model returns relation´s dynamic attributes but null relation

I have set 2 models (Post and Category) with it´s proper relationships configured
class Post extends Model
{
protected $fillable = [
'title',
'excerpt',
'body',
'featured',
'published',
'category_id',
];
public function category()
{
return $this->belongsTo('App\Category');
}
}
class Category extends Model
{
protected $fillable = [
'name',
];
public function posts()
{
return $this->hasMany('App\Post');
}
}
And my Post´s storing method is
public function store(Request $request)
{
$post = Post::create($request->all());
return redirect('admin/posts');
}
The thing is, it´s actually working ok, it sets the category_id on the table and I can fetch all the dynamic data by using $post->category->name, but when I var_dump($post->relation) I get a null return.
I if create a new Post model, set all the attributes, save it and then associate the Category model (as documented on the official channel), it will return everything as expected.
For now, all I need is to fetch it´s dynamic attributes, and it´s working fine now, but I know I must be doing something wrong to get the null response. My concern is that it may be working fine now, but when the project gets larger I´ll probably face a bigger problem and I´ll have a lot of work to fix this issue.
The relation isn't there because you haven't loaded it. All it knows is the foreign key. It would be wildly inefficient if it grabbed all that information for you because it wouldn't always need all that. Think of instances where a single model could have many relationships, that would be many database calls for no reason.
If you need the relation, you can use $post->category. Since the relation is not yet loaded, it will get it for you when you do this.
Or you can eager load it by using the following $post->load('category') although this doesn't really benefit you because you are working with a single Post at this point. If you had a collection of Post objects, then you'd start seeing the benefits of using $posts->load('category') otherwise you end up with the n + 1 problem.
Consequently, if you use $post->load('category') and then var_dump($post), you should see that the relation is no longer null.

Getting specific columns from Laravel Eloquent

I've been beating myself up with this and can't seem to be able to get my JSON to only display the title and description of the rooms should they be live. I have tried using return $this->hasMany('Room')->select(array('id', 'title', 'description')); but it returns nothing at all for rooms.
Can anyone help? I'm sure this must be very simple to achieve as I understood Laravel Eloquent to be simplistic for this kind of task.
JSON
[
{
id: 1,
building_title: "Drum Castle"
room: [
{
id: 1,
building_id: 7,
title: "Snooker Room",
description: "Full Description",
live: 1
}
]
}
]
Building Model
public function room()
{
return $this->hasMany('Room');
}
Room Model
public function building()
{
return $this->belongsTo('Building', 'building_id');
}
Controller
$buildings = Building::with('room')->get();
Your attempt at restricting the fields on the relationship failed because you didn't select the building_id field. If you don't get this field, Laravel has no idea on which rooms belong to which buildings (think about eager loaded relationships).
One method to do what you want is to override the toArray() method (which is called by toJson()), on either the Building or the Room.
Another option is to set the hidden/visible attributes on your Room model. The attributes will govern which fields are hidden/visible when converting to an array.
class Room extends Eloquent {
protected $hidden = array('building_id', 'live');
// or
protected $visible = array('id', 'title', 'description');
// rest of class
}

Many-to-Many and Eager loading query

I am new with Laravel, I was able to query Many-to-Many relationships. Where 'template_dynamic' is the pivot of two tables 'template' and 'dynamic'.
// Template Model
class Template extends Eloquent
{
protected $table = 'template';
protected $guarded = array('template_id');
protected $primaryKey = 'template_id';
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->select('*')
->withPivot('template_dynamic_id')
->orderBy('template_dynamic_html_sort', 'ASC');
}
here I was able to retrieve the records
// Template Controller
$dynamic_fields = Template::find($rec->template_id)->dynamic;
what I want to do now is that pivot table has-many properties 'template_dynamic_option'. How will I query the records and combine it with $dynamic_fields variable?
// What I want to do is something like this. But sadly this is an invalid syntax
$dynamic_fields = $dynamic_fields->with('template_dynamic_option');
Any recommendation or enhancements are welcome.
Thank you in advance.
First, I am pretty sure you don't need the select('*') in your relationship query there.
But let's get to your actual problem ;)
To access the pivot table in Eloquent is pretty simple.
$dynamic_fields = Template::find($rec->template_id)->dynamic;
foreach($dynamic_fields as $dynamic){
var_dump($dynamic->pivot)
}
The thing is though, by default only the keys of the pivot table are present in the object.
To change that you have to define them with withPivot(). Actually like you already did but not with the id.
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->withPivot('template_dynamic_option')
->orderBy('template_dynamic_html_sort', 'ASC');
}
And if you have multiple additional columns use this syntax:
->withPivot('template_dynamic_option', 'foo', 'bar');

Resources