Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

404 error when submitting user form in the registrationController laravel

Tags:

php

laravel

I get a 404 error when I try to insert user's details into multiple tables during registration my user model:

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash; 


class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username','accno', 'email', 'password', 'role', 'status', 'activation_code'
     ];

     protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // a mutator for the email attribute of our model with email validation check and check to avoid duplicate email entries.

    protected $table = 'users';

    public $timestamps = false;

    public $incrementing = false;

    public function setEmailAttribute($email)
    {
        // Ensure valid email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \Exception("Invalid email address.");
        }

        // Ensure email does not exist
        elseif (static::whereEmail($email)->count() > 0) {
            throw new \Exception("Email already exists.");
        }

        $this->attributes['email'] = $email;
    }

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = Hash::make($password);
    }

    public function profiles()
    {
        return $this->hasOne(profiles::class);
    }

    public function accounts()
    {
        return $this->hasOne(accounts::class);
    }

    public function transactions()
    {
        return $this->hasMany(transactions::class);
    }
}

I try refactoring by separating my validation code from my logic using RegisterUserTrait

<?php

namespace App\Traits;

use App\User;
use App\Profile;
use App\Account;
use Keygen;

trait RegisterUser
{
    public function registerUser($fields)
    {   
       
        
            $user = User::create([
                
                'username'      => $fields->username,
                'accno'        =>  $this->generateAccountNumber(),
                'email'      => $fields->email,
                'password'  => $fields->password = bcrypt(request('password')),
                'roles'  => $fields->roles,
                'activation_code' =>  $this->generateToken()
            ]);
    
            Profile::create([
                'accno' => $user->accno,
                'username' => $user->username,
                'acc_type'      => $fields->acc_type,
                'firstname'      => $fields->firstname,
                'lastname'      => $fields->lastname,
                'nationality'     => $fields->nationality,
                'occupation'     => $fields->occupation,
                'address'     => $fields->address,
                'city'     => $fields->city,
                'state'     => $fields->state,
                'zipcode'     => $fields->zipcode,
                'phoneno'     => $fields->phoneno,
                'dob'     => $fields->dob,
                'gender'     => $fields->gender,
                'martial_status'     => $fields->martial_status,
                'user_image'     => $fields->user_image,
            ]);
            
            Account::create([
                'accno' => $user->accno,
                'username' => $user->username,
            ]);

            return $user;
        
    }

then storing the data using my registrationController:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\RegistrationRequest;
use App\Traits\RegisterUser;

class RegistrationController extends Controller
{
    use RegisterUser;

    public function show()
    {
        return view('auth/register');
    }

    public function register(RegistrationRequest $requestFields)
    {
      //calling the registerUser method inside RegisterUser trait.
      $user = $this->registerUser($requestFields);
        
      return redirect('/login');
    

     }
}

but when I register the user, the data is only saved in the create_user_table and return a 404 page not found error. How can I save the data to the selected table and redirect to the login page?

like image 820
Toby Nwude Avatar asked Apr 10 '20 04:04

Toby Nwude


Video Answer


1 Answers

As fa as i can see this is not true for foreign key relations in User Model

public function profiles()
{
    return $this->hasOne(profiles::class);
}

public function accounts()
{
    return $this->hasOne(accounts::class);
}

public function transactions()
{
    return $this->hasMany(transactions::class);
}

it should be as follows;

public function profiles()
{
    return $this->hasOne(Profile::class);
}

public function accounts()
{
    return $this->hasOne(Account::class);
}

public function transactions()
{
    return $this->hasMany(Transaction::class);
}
like image 81
Furkan ozturk Avatar answered Oct 03 '22 16:10

Furkan ozturk