Saving two models to sync into pivot table - php

I have a request controller that has two Model to be save for me able to sync this into my pivot table. I still don't have idea how I'm gonna sync one of the two Models in my Controller. I have Documents and Approves M:M relationship with a pivot table approve_document
Model
Document:
public function approves()
{
return $this->belongsToMany('App\Models\Document', 'approve_document');
}
Approve:
public function pendingDocuments()
{
return $this->belongsToMany('App\Models\Document', 'approve_document');
}
Controller:
$document = new Document();
$approve = new Approve();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$approve->approver_id = $request->approver;
$approve->save();
$document->save();
$document->approves()->sync([$approve],false);
Honestly here I still don't have idea what should I put inside my sync array. It throws me a error Illegal offset type. Any help to correct my error?
Update

sync() Method accepts the ids of the Models to be attached.
So, in your case sync() method will need id of the approve model.
$document->approves()->sync([$approve->id],false);
//assuming id is the PK for your Approve model
Reference: Inserting Related Models

Related

How to add pivot table when inserting data to database in Laravel 8

maybe someone know how to insert pivot table in Laravel 8 automatically every i insert counselings table?
I have Model Counseling n to n Problem,
Input form
counselings table
problems table
Counselings Model
Problem Model
Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class', 'counselings')->findOrFail($request->id);
return response()->json($student);
}
public function store(Request $request)
{ dd($request->all());
$counseling = new Counseling();
$counseling->student_id = $request->student_id;
$counseling->user_id = Auth::user()->id;
$counseling->save();
if ($counseling->save()) {
$problem = new Problem();
$problem->id = $request->has('problem_id');
$problem->save();
}
}
You can insert into a pivot table in a few different ways. I would refer you to the documentation here.
Attaching
You may use the attach method to attach a role to a user by inserting
a record in the relationship's intermediate table:
Example:
$problem->counselings()->attach($counseling->id);
Sync
You may also use the sync method to construct many-to-many
associations. The sync method accepts an array of IDs to place on the
intermediate table. Any IDs that are not in the given array will be
removed from the intermediate table.
Example:
$problem->counselings()->sync($counselingsToSync);
Toggle
The many-to-many relationship also provides a toggle method which
"toggles" the attachment status of the given related model IDs. If the
given ID is currently attached, it will be detached. Likewise, if it
is currently detached, it will be attached:
Example:
$problem->counselings()->toggle($counselingsToToggle);
I would change your store() method to something like this :
public function store(Request $request)
{
$counseling = Counseling::create([
'student_id' => $request->student_id,
'user_id' => Auth::user()->id
]);
if($request->has('problem_id'){
$counseling->problems()->attach($request->problem_id);
//return something if problem id is in request
}
//return something if problem id is not there
}

Return only specific columns of a polymorphic relationship? Laravel

is there any way that I can only get specific columns back of my polymorphic relationship?
I want to make an Api Call to retrieve a Customer but I dont want to retrieve all the data of the User just the id and the username of it.
Here ary my Models:
User:
public function userable()
{
return $this->morphTo(__FUNCTION__, 'model_type', 'model_id');
}
Customer:
public function user()
{
return $this->morphOne(User::class, 'model');
}
I dont want to work with hidden inside of the User Model because for other Api Calls i need all information of the User.
You can use this method to get the value of attributes in polymorphic relations:
$customer = new Customer();
$customer->user()->value('your_key');

how to access the one to many model relation in laravel,with access all the columns

I am creating a comment table in my Laravel project so that users can comment on products. I want to make a table which can integrate with my user table (like a one-to-many relationship) in Laravel.
Here is my code:
public function buyproduct($id){
$user = Auth::user();
$users_comment = User::with('comments')->get();
$comments =comments::orderBy('id','desc')->get();
$renimage = Clothes::where('id',$id)->first();
return view('pages.products',[
'renimage'=>$renimage,
'google_avater'=>$user,
'comments'=>$users_comment
]);
}
Here I send my data to the view in my project. I don't understand how to access the data which is in my user table along with the data in the comment table.
First comments::orderBy... should be Comments::orderBy... ,
But you don't need that,
It's so simple to get user comments :
First Method: Using with()
Once the relationship has been defined, we can access the collection of comments by accessing the comments property. Remember, since Eloquent provides "dynamic properties", we can access relationship methods as if they were defined as properties on the model:
$books = App\Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
Second Method : Direct
Thankfully, we can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eager loaded using the with method:
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
//
}
In your case :
public function buyproduct($id){
$user = Auth::user();
$users_comment = User::with('comments')->get();
//blow line changed
$comments =$users_comment->comments;
$renimage = Clothes::where('id',$id)->first();
return view('pages.products',[
'renimage'=>$renimage,
'google_avater'=>$user,
'comments'=>$users_comment
]);
}
Hope it helps;)

Laravel insert relationship in newly created model

I have a relationship set up between two models. The two models are set up like:
app/Character.php
public function characteristics() {
return $this->hasMany('App\Characteristics');
}
app/Characteristics.php
public function character() {
return $this->belongsTo('App\Character');
}
then in a controller I have a method to create a new character with a predetermined set of characteristics as follows:
app/Http/Controllers/CharacterController.php
public function newCharacter(Request $request) {
$character = new Character();
$characteristics = getCharacteristics($character->id);
// Save basic character stuff
$character->characteristics()->saveMany($characteristics);
$character->save();
}
The highlighted line is throwing an error because saveMany is not a function of Builder so how can I get the created character without having to do a find that would have to hit the database again?
I think you need to save the character model first, because if you're building a hasMany/belongsTo relationship your characteristics table must have a column for character_id, and when you do $character->characteristics()->saveMany($characteristics); Laravel will try to insert the ID from the parent model. And as per the code shared by you, you've just instantiated the model, by this point of time it doesn't have an ID associated with it. So you need to save the character model first and assuming the getCharacteristics() method is returning an array/collection of Characteristics Models, Following should work:
public function newCharacter(Request $request) {
$character = new Character();
$character->save();
$characteristics = getCharacteristics();
// Save basic character stuff
$character->characteristics()->saveMany($characteristics);
}
And to further clarify this for you, from the characteristics method in your Character model an instance of HasMany not a Builder is being returned, thus saveMany works here.

Laravel ORM problems

I can't figure how to relate these two tables.
I'm new to Laravel and ORM so it's kind of hard to me.
Here's my 2 tables I'm trying to relate:
Tables are called: posts and post_categories
And here are some of the code:
class Post extends Eloquent {
public function categories()
{
return $this->hasOne('PostCategorie');
}
}
class PostCategorie extends Eloquent {
protected $table = 'post_categories';
public function post()
{
return $this->belongsTo('Post', 'pc_id');
}
}
public function postCreate()
{
$validator = Validator::make(Input::all(), Post::$rules);
if ($validator->fails())
{
return Redirect::action('PostsController#getCreate')->withInput()->withErrors($validator);
}
// Else add to DB
$categories = Input::get('categories');
$post = new Post;
$post->user_id = Auth::user()->id;
$post->title = Input::get('title');
$post->text = Input::get('text');
$post->categories()->id_1 = $categories[0];
$post->save();
}
So as you see. I pass values to post and when I save it's ok... but I can't add categories ID to another table...
And also I created dummie entries, and tried to get Post Categories values:
Route::get('/', function()
{
$post = Post::find(5);
echo $post->title;
echo $post->categories()->id_1;
});
But it failed:
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$id_1
OK first things first, You dont have to use PostCatagorie as your model name. Laravel features a pretty good pluralization class and can quite happily deal with Category or PostCategorie. Additionally, if you just call pc_id category_id (assuming a table name of category) you wont have to define any foreign keys which will make life a bit simpler until you get to grips with the basics.
When you create any kind of object (e.g $post) you can check if its relations are attached using dd($post); you can drill down further into these relations with:
echo '<pre>';
print_r($post);
echo '</pre>;
This together will allow you to see if what you are trying to do is actually working and view the structure of your result object.
I'm not entirely sure what you mean by "I cant add categories id to another table", and you seem to be saving the data ok... so I'll skip that bit. Please clarify the question if you need more info.
Once you have got the relationships set up and got some data in there you would have to load the two models together like so to get an object with the attached relationship:
$post = Post::with('Category')->find(5);
You will then be able to access your category object as $post->Category and from there any of its properties, e.g. $post->Category->id

Categories