Skip to content
Advertisement

values are not inserting in profile table

use AppUserProfile;
use AppPost;

class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

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

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

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

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // AppUser::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id','id');
    }
    public function history()
    {
        return $this->hasOne(UserHistory::class,'user_id','id');
    }
}

This is the User model

class UserProfile extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}

This is the UserProfile model

class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}

This is the Country model

    public function create()
    {
        //
        $roles = AppRole::all();
        $countries = AppCountry::all();
        return view('dashboard.users.create',compact('countries','roles'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {

        $user = [
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ];

        $user = AppUser::create($user);
               $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
        if ($request->hasFile('photo')) 
         $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
     else
        $filename = "profiles/dummy.jpg";

    if ($user) {
        $profile = new AppUserProfile([
            'user_id' => $user->id,
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);

        $user->profile()->save($profile);
        $user->roles()->attach($request->roles);


        return redirect()->route('users.index');
    }

}

This is the UserContrller

@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf
    <div class="form-row align-item-center">
        <div class="col-md-12">
            <label for="inputUsername"> Name</label>
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">
        </div>
        <div class="col-md-12">
            <label for="inputName">Full Name</label>
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">
        </div>
        <div class="col-md-12">
            <label for="inputUserEmail">Email</label>
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">
        </div>
        <div class="col-md-12">
            <label for="inputPassword">Password</label>
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">
        </div>
        <div class="col-md-12">
            <label for="inputPhone">Phone</label>
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">
        </div>
        <div class="col-md-12">
            <label for="selectCountry">Select Country</label>
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 mt-3">
            <label for="inputCity">City</label>
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">
        </div>
        <div class="col-md-12">
            <label for="selectRoles">Select Roles</label>
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 my-3">
            <label for="inputFileName">Profile Image</label>
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">
        </div>
        <div class="col-md-12">
        <button type="submit" class="btn btn-primary mb-2">Add New User</button>
    </div>
</div>
</form>
@endsection

This is the create view

I have used this code for inserting values into two tables one table is user table and second userprofile table using relationships.In user table values are inserting successfully but values are not inserting in profile table.

Advertisement

Answer

try this create() function ref link https://laravel.com/docs/5.7/eloquent-relationships#the-create-method

 $profile = AppUserProfile::create([
            'user_id' => $user->id,
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);

full controller will be

public function storeA(Request $request)
    {

        $user = [
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ];

        $user = AppUser::create($user);
        $filename = sprintf('thumbnail_%s.jpg', random_int(1, 1000));
        if ($request->hasFile('photo'))
            $filename = $request->file('photo')->storeAs('profiles', $filename, 'public');
        else
            $filename = "profiles/dummy.jpg";

        if ($user) {
            $profile = AppUserProfile::create([
                'user_id' => $user->id,
                'city' => $request->city,
                'country_id' => $request->country,
                'photo' => $filename,
                'phone' => $request->phone,
            ]);

            $user->roles()->attach($request->roles);


            return redirect()->route('users.index');
        }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement