Search code examples
model-view-controllereloquentlaravel-8eloquent-relationship

Laravel 8 multiple models to single view Error $address Not defined


I'm trying to create 2 rows in the DB using findOrNew() but when I use the ID from the Users model to create another model(Address) the programs returns undefined variable $address. I don't know if I'm using the correct approach or not. Bellow you can view my approach. Can you lead me to the right approach or where to find it?

2 models one view:

enter image description here


Solution

  • seeing what you have in your method is returning an undefined because it is not executing the findOrNew method correctly, check this link, maybe it will help you and this same

    the second is that if you are passing the values by post everything will come to you in the $req parameter and only there then if you want to use the id you would have to access through $req->id if you send the data correctly

    the third I see that in the view method you are passing 3 parameters when you should only pass two the first the name of the view the second the arrangement with the data that you will pass to the view

    public function detail(Request $req)
    {
        $user = User::firstOrNew($req->id);
        $user->user_type_id = 1;
        $user->name = $req->name;
        $user->last_name = $req->last_name;
        $user->email = $req->email;
        $user->password = Hash::make(Str::random(8));
        $user->save();
    
        $address = UserAddress::firstOrCreate(['user_id' => $req->id]); //or maybe $user->id
    
        return view('user.detail', [
            'user' => $user,
            'adderss' => $address
        ]);
    }
    

    finally you may prefer to use the updateOrCreate method

    public function detailV2(Request $req)
    {        
        $user = User::updateOrCreate(
            ['id' => $req->id],
            [
                'user_type_id' => 1,
                'name' => $req->name,
                'last_name' => $req->last_name,
                'email' => $req->email,
                'password' => Hash::make(Str::random(8)),
            ]
        );
    
        $address = UserAddress::firstOrCreate(['user_id' => $user->id]);
    
        return view('user.detail', [
            'user' => $user,
            'adderss' => $address
        ]);
    }