In my destroy function of my controller, I'm attempting to take a copy of my object (model with one relationship) and insert it into another database before deleting it. However only the model is being created and not the relationship. Why is this happening?
Destroy function:
public function destroy($id)
{
$user = User::with('Phone')->find($id);
$archive = $user->replicate();
$archive ->changeConnection('mysql2');
$archive ->push();
}
User model:
public function phone()
{
return $this->hasOne('App\Phone');
}
Phone model:
public function user()
{
return $this->belongsTo('App\User');
}
When I insert via the store function in my controller, it sets up the relationship just fine:
public function store(Request $request)
{
// Validation has passed, insert data into database
$user= User::create($request->all());
$user->Phone()->create($request->all());
}
Related
I have 2 models: one for users and one for clients. A user is a customer
User has a 'codigocli' field and client has a 'codigo' field
The relationships between my models are like this:
//User model
public function cliente()
{
return $this->hasOne(Cliente::class, 'codigo', 'codigocli');
}
//Cliente model
public function user()
{
return $this->belongsTo(User::class, 'codigocli', 'codigo');
}
My database is fine (I think) client has the 'codigo' field and users has the 'codigocli' field. So what am I doing wrong? When I want to query my home.blade.php with dd(auth()->user()-cliente()) I don't get anything, although it shows me the parent object fine.
H
You have an OneToOne relationship here so try this if you don't change id name:
//User model
public function cliente()
{
return $this->hasOne(Cliente::class, 'codigocli');
}
//Cliente model
public function user()
{
return $this->belongsTo(User::class, 'codigocli');
}
if you change id name:
//User model
public function cliente()
{
return $this->hasOne(Cliente::class, 'codigocli','local_id_name' );
}
//Cliente model
public function user()
{
return $this->belongsTo(User::class, 'codigocli', 'local_id_name');
}
I have 3 tables:
users
id
role
email
typable_id
typable_type
buyers
id
name
address
avatar
email
residential_id
residentials
id
name
city
state
And here is my model that shows the relationship
User.php
public function typable()
{
return $this->morphTo();
}
Buyer.php
public function residential()
{
return $this->belongsTo(Residential::class);
}
public function user()
{
return $this->morphMany(User::class, 'typable');
}
Residential.php
public function buyer()
{
return $this->hasMany(Buyer::class);
}
If I want to delete the residential, all buyers from that residential need to be deleted. Same as users need to be deleted too when the buyers is deleted. How can I do that? This is what insides my Residential Controller for destroy function.
ResidentialController
public function destroy(Request $request)
{
$residentials = Residential::find($request->input('id'));
$residentials->id = $request->input('id');
$residentials->name = $request->input('name');
$residentials->delete($residentials);
return response()->json($residentials);
}
I have tried to put this code to delete the buyers (for users not yet) inside destroy() but nothing is changed for the buyers to be deleted.
$buyers = Buyer::where('residential_id','=',$request->residential_id)->first(); $buyers->delete($buyers);
While this is the code that I managed to do if I want to delete the buyers, the users are deleted too.
BuyerController
public function destroy(Request $request)
{
$users = User::where('email', '=', $request->email)->first();
$buyers = Buyer::find($request->input('id'));
$buyers->id = $request->input('id');
$buyers->name = $request->input('name');
$buyers->delete($buyers);
$users->delete($users);
return response()->json($buyers);
}
I hope there is someone to help and teach me the correct way.
Approach-1
you can override the delete function for any model.
//Residential.php
public function delete()
{
$this->buyer->delete();
return parent::delete();
}
//Buyer.php
public function delete()
{
$this->user->delete();
return parent::delete();
}
Now when you delete any Residential record, the chain will first delete any related user and then delete buyer and finally delete the Residential record.
Approach-2
You can use each() method to get all relating buyer and then get all relating user.
$residentials->buyer
->each(function ($b) {
$b->user->each(function ($u) {
$u->delete();
});
$b->delete();
});
$residentials->delete();
You might want to register model events to handle that:
class Residential extends Model
{
// Lets use plural form for a HasMany relationship.
public function buyers()
{
return $this->hasMany(Buyer::class);
}
protected static function booted()
{
static::deleting(function ($user) {
// I am using Higher Order Message, check this out: https://laravel.com/docs/8.x/collections#higher-order-messages
$this->buyers->each->delete();
});
}
}
class Buyer extends Model
{
// Lets use the plural form for a MorpMany relationship.
public function users()
{
return $this->morphMany(User::class, 'typable');
}
protected static function booted()
{
static::deleting(function ($user) {
$this->users->each->delete();
});
}
}
And you only have to remove a single object in your controller:
class ResidentialController
{
public function destroy(Request $request)
{
$residential = Residential::findOrFail($request->input('id'));
$residential->delete();
// The framework is gonna automatically convert this to a JSON object.
return $residential;
}
}
class BuyerController
{
public function destroy(Request $request)
{
$buyer = Buyer::findOrFail($request->input('id'));
$buyer->delete();
// The framework is gonna automatically convert this to a JSON object.
return $buyer;
}
}
I have model user and user_data. I want to take some data from user and user data. My code looks like:
User model:
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id');
}
public function getUserById($id)
{
$user = User::findOrFail($id);
return $user;
}
UserData model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
User controller
public function getUser($id)
{
//$user = $this->model->getUserById($id);
$user = User::with('user_data')->find(3);
dd($user->sex);
return view('user', compact('user'));
}
How I can get data from two tables? When i dump sex i get null, but I have it in db.
you have to add also the local key in the relationship like this
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id','your local key');
}
$user = User::with('user_data')->where('id',$id)->first(); // Get the data like this
After that you can check what is it in like this
$user->user_data[0]->sex // Not $user->sex
If it's not working try to swap the foreign key and local key places.
Also you have to take the data like this
I want to display the name of the user in the blade using Eloquent: Relationships. My code's can display data using relationship but if the data is soft deleted it gives me a error.
Here's my code.
// History Model//
public function user()
{
return $this->belongsTo(User::class);
}
// User model //
public function history()
{
return $this->hasMany(History::class);
}
// Controller //
public function index()
{
$histories = History::find(3);
return view('booking.backend.content.history.index', compact('histories'));
}
// index.blade //
{{$history->user->name}}
I already fixed it.
In my model history I add withtrashed.
public function history()
{
return $this->hasMany(History::class)->withTrashed();
}
i have two table
posts
id|post_title|post_content
post_images
id|images|post_id
Controller
public function AddPost(Request $request)
{
Post::create($request->all());
// PostImage::create();
return Redirect::to('Post');
}
Also i have added Relation
class Post extends Model
{
protected $table = 'posts';
public function images()
{
return $this->hasMany('App\PostImage');
}
}
class PostImage extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
I have one form where i adding post title ,post content and selecting multiple images. My question is how I can store post images along with post id in post_images table?
In you controller AddPost function try (using Form model binding)
$post = new Post($request->all());
PostImage::post()->images()->save($post);
Or you can also do like this I think
public function AddPost(Post $post, Request $request)
{
$input = Input::all();
$input['post_id'] = $post->id;
PostImage::create( $input );
return Redirect::to('Post');
}