Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Qlic's avatar
Level 18

Mass Assignment update gives no feedback

Hello,

I am attempting to update a table using an eloquent model. However, it gives me no feedback, i tried several things but i can;t figure out whats wrong here.

Student::findOrFail(Auth::user()->student->id)->update($request->all());
dd('sadsada');
 //Auth::user()->student->update($request->all());

If i place a diedump before the update command, it gets shown, if i place it below the update nothing, the page just refreshes. I tried two methods, both have the same behaviour. Also i did a diedump on Auth::user()->student, that returns a collection as it should.

In the Student model, i have defined the $fillable array.

Now i'm not sure wether the method is allowed for an update, or if its create only. I wanted to try this to prevent me having to define all update fields manually.

0 likes
38 replies
bimalshah72's avatar

@Qlic

Auth::user()->student returns collection - hence you need to iterate collection and then take id -- you should never have id - user()->student->id never work as user()->student is collection

hence findorfail fails and get back to your original page

davorminchorov's avatar

Are you trying to update multiple users at the same time or are you trying to update a single student?

You need only 1 ID which is usually passed through the URL in the controller.

Qlic's avatar
Level 18

@bimalshah72 Thank you for your response, however i have to admit i don't exactly know what you mean (english is not my mother language). Is the conclusion that a mass assignment update is not possible, and i should assign the update values like this?

$student = Student::where('user_id', Auth::user()->id)->first();
$student->firstName = '';
etc.
$student->save();
bimalshah72's avatar

@Qlic

What is your table structure? do you have two different table, student and user?

Could you paste here your model classes?

Qlic's avatar
Level 18

@bimalshah72 the sturcture is as follows:

Each user has an entry in the "users" table, this table has a field called 'type', which can contain one of the following values: student, expert, organization. Based on this value, the actual profile will be made in one of three tables (students, experts, organizations).

User -> Student

User -> Expert

User -> Organization

Student Model

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * Class Student
 * @package App
 */
class Student extends Model {

    protected $dates = [
        'graduationDate',
        'created_at',
        'updated_at'
    ];

    /**
     * @var array
     */
    protected $fillable = [
        'user_id',
        'salutation',
        'initials',
        'firstName',
        'insertion',
        'lastName',
        'phone',
        'mobile',
        'institute',
        'address',
        'zipcode',
        'city',
        'country',
        'studyStage',
        'graduationDate',
        'certificate',
        'involvementShort',
        'involvementLong',
        'involvementJob',
        'involvementAdvice',
        'shortScription',
        'masterProject',
        'promotion',
        'postdoc',
        'phd',
        'interests',
        'motivation',
        'agreeTerms',
        'agreeConfidential',
        'agreeNews'
    ];


    public function setGraduationDateAttribute($value)
    {
        $this->setAttribute('graduation_date', $value ? $value : null);
    }

    /**
     * A Student belongs to a users account
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * A student can have many expertises
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function expertise()
    {
        return $this->belongsToMany('App\Expertise')->withTimestamps();
    }

    /**
     * Get a list of expertise ids associated with the current student
     *
     * @return array
     */
    public function getExpertiseList()
    {
        return $this->expertise->lists('id')->all();
    }

    /**
     * A student can have many skills
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function skill()
    {
        return $this->belongsToMany('App\Skill')->withTimestamps();
    }

    /**
     * Get a list of skill ids associated with the current student
     *
     * @return array
     */
    public function getSkillList()
    {
        return $this->skill->lists('id')->all();
    }

    /**
     * A student can have one institution
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function institution()
    {
        return $this->hasOne('App\Institution', 'id', 'institute');
    }

}

User Model

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

/**
 * Class User
 * @package App
 */
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

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

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token'
    ];


    /**
     * Hash the password.
     *
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        // if you want it to be fillable, then to avoid resetting with empty string:
        if ( ! $value && isset($this->attributes['password']))
        {
            unset($this->attributes['password']);
        }
        else
        {
            $this->attributes['password'] = \Hash::make($value);
        }
    }

    /**
     * A user could be a student
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function student()
    {
        return $this->hasOne('App\Student');
    }

    /**
     * A user could be an expert
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function expert()
    {
        return $this->hasOne('App\Expert');
    }


    public function correspondences()
    {
        return $this->hasMany('App\Correspondence');
    }

    /**
     * A user could be an organization
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function organization()
    {
        return $this->hasOne('App\Organization');
    }

    /**
     * A user can have many languages
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function language()
    {
        return $this->belongsToMany('App\Language')->withPivot('level')->withTimestamps();
    }

    /**
     * A user can have many filters
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function projectFilter()
    {
        return $this->hasMany('App\ProjectFilter');
    }

    /**
     * A user can have many favorites
     *
     * @return mixed
     */
    public function projectFavorite()
    {
        return $this->hasMany('App\ProjectFavorite');
    }

    /**
     * A user can have many communications
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function projectCommunication()
    {
        return $this->hasMany('App\ProjectCommunication');
    }

    /**
     * A user can belong to many organization favorites
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function OrganizationFavorite()
    {
        return $this->belongsToMany('App\OrganizationFavorite');
    }

    /**
     * A user can have many notes
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function note()
    {
        return $this->hasMany('App\UserNote');
    }
}


bimalshah72's avatar

@Qlic

Since it is one to one relationship, I think this should work

Auth::user()->student()->update($request->all());
dd('sadsada');
bimalshah72's avatar

@Qlic

Above solution is - provided that logged in user or authenticaed user is of type studen

Qlic's avatar
Level 18

@bimalshah72 in my first post you can see i already tried that, and altough i think it used to work, now however it doesn't, it just reloads the page.

@thomaskim i tried your method, this also does not store the date, it just reloads the page without any errors.

Qlic's avatar
Level 18

@bimalshah72 correction, i see you have student() where i had student, your method works!

pmall's avatar

What the hell is this ^^ :

Student::where('user_id', Auth::user()->id)->firstOrFail();

Use :

$student = Auth::user()->student; // assuming it is a belongs to / has one relationship
$student->fill($request->all()); // Assuming the $fillable array attribute is set
$student->save();

I think you can even do

Auth::user()->student->update($request->all());
Qlic's avatar
Level 18

@bimalshah72 @pmall @thomaskim i was premature to say it worked, i thought it did because the value i had in the input field remained the same after submitting, but that was due to a validation error.

So i'm back to square one, i tried all of the above solutions, and none works for me.

  • I get no errors
  • I know the post passes validation
  • I have the post data in the $request->all() variable
  • I have the students data in the $student variable
  • I have the $fillable set on the model

I really don;t know what else i could be missing here :(

The only thing that worked as a test was:

$student = Student::where('user_id', Auth::user()->id)->first();
$student->studyStage = 'test';
$student->save();
pmall's avatar

This is not working ?

$student = Auth::user()->student; // assuming it is a belongs to / has one relationship
$student->fill($request->all()); // Assuming the $fillable array attribute is set
$student->save();

First, is the user / student relationship a one to one ? It is unclear.

What happen ? The page just keep going and the value don't get updated ?

Qlic's avatar
Level 18

@pmall

I tried it and did not seem to work.

User model

/**
     * A user could be a student
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function student()
    {
        return $this->hasOne('App\Student');
    }

Student model

/**
     * A Student belongs to a users account
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
pmall's avatar

You have a lot of fields in fillable. Be careful there is not a typo.

Qlic's avatar
Level 18

I will double check them, however if i did make a typo in one of them, shouldn't it just skip that one and still fill the others?

pmall's avatar

shouldn't it just skip that one and still fill the others?

No it should throw a mass assignment exception. Try to catch an exception around your code block.

Qlic's avatar
Level 18

I tried a try/catch, but i get no response. This is my current update:

$student = Student::find(Auth::user()->student->id);
$student->update($request->all());

If i diedump above the update command, it diedumps. If i diedump after the update command it does not diedump.

pmall's avatar

Can you dump the student attributes ($student->getAttributes()) before and after assigning the value with $student->fill() (like my previous code)

Qlic's avatar
Level 18

Before:

array:33 [▼
  "id" => 1
  "user_id" => 3
  "salutation" => 0
  "initials" => "F"
  "firstName" => "Fake"
  "insertion" => ""
  "lastName" => "Name"
  "phone" => "0123456789"
  "mobile" => "0123456789"
  "institute" => 85
  "address" => ""
  "zipcode" => ""
  "city" => ""
  "country" => "NL"
  "studyStage" => "dsfdsf"
  "graduationDate" => null
  "certificate" => ""
  "involvementShort" => 1
  "involvementLong" => null
  "involvementJob" => 1
  "involvementAdvice" => null
  "shortScription" => null
  "masterProject" => 1
  "promotion" => null
  "postdoc" => 1
  "phd" => 0
  "interests" => ""
  "motivation" => "My motivation"
  "agreeTerms" => "2015-08-17 00:00:00"
  "agreeConfidential" => "2015-08-17 00:00:00"
  "agreeNews" => "2015-08-17 00:00:00"
  "created_at" => "2015-08-13 16:53:33"
  "updated_at" => "2015-08-19 10:35:07"
]

If i place the diedump after the fill command, it does not seem to trigger.

pmall's avatar

There must be something in the log or an exception thrown. We cant help you without this.

Qlic's avatar
Level 18

I empty'd out todays log, than submitted the form again, log stays empty. Perhaps i made a wrong exception, to be sure could you tell me how you would do it?

pmall's avatar
try
{
    // Your code
}

Catch (\Exception as $e)
{
    dd($e);
}
veve286's avatar

Just check ur request

dd($request->all( ) );

And show me the results.

Qlic's avatar
Level 18

@pmall i tried the try/catch you posted, but got no error, the page just reloads without any message.

@veve286

array:29 [▼
  "_method" => "PATCH"
  "_token" => "gw612sdAUwNbH77u5W5pGTj26GyfIhHps4sYrn9E"
  "salutation" => "0"
  "phone" => "0123456789"
  "initials" => "F"
  "mobile" => "0123456789"
  "firstName" => "Fake"
  "institute" => "85"
  "insertion" => ""
  "studyStage" => "dsfdsf"
  "lastName" => "Name"
  "graduationDate" => ""
  "address" => ""
  "city" => ""
  "zipcode" => ""
  "country" => "NL"
  "certificate" => "dsfdsfds"
  "description" => "<p><br></p>"
  "files" => ""
  "skills" => array:2 [▼
    0 => "3"
    1 => "5"
  ]
  "languages" => array:3 [▼
    0 => "16"
    1 => "4"
    2 => "3"
  ]
  "languagesLevel" => array:3 [▼
    0 => "4"
    1 => "3"
    2 => "1"
  ]
  "phd" => "0"
  "interests" => ""
  "motivation" => "My motivation"
  "expertise" => array:2 [▼
    0 => "3"
    1 => "2"
  ]
  "involvementShort" => "1"
  "involvementJob" => "1"
  "masterProject" => "1"
]

Here is the complete update function

    public function update(StudentRequest $request)
    {
        if (Auth::user()->student === null)
        {
            Student::create($request->all() + ['user_id' => Auth::user()->id]);
        }
        else
        {
            $student = Auth::user()->student;
            $student->fill($request->all());
            $student->save();
        }

        $student = User::find(Auth::user()->id)->student;
        $this->syncExpertise($student, $request);
        $this->syncSkills($student, $request);

        $lang = [];

        if ($request->input('languages'))
        {
            foreach ($request->input('languages') as $key => $value)
            {
                if (!empty($value))
                {
                    $lang[$value] = ['level' => $request->input('languagesLevel')[$key]];
                }
            }
        }

        User::find(Auth::user()->id)->language()->sync($lang);

        Flash::success(trans('message.updateStudentSuccess'));
        return redirect()->route('student.edit');
    }
veve286's avatar

try this $userId=Auth::user( )->id; $user=User::findOrFail($userId); $user->student( )->update( $request->all( ) );

or

$userId=Auth::user( )->id; $student=Student::where('user_id',$userId ); $student->update( $request->all( ) );

i think u cant access student object directly from Auth::user( )->student like this. u can only retrieve user data from user table .It cant retrieve relationship data. But i may be wrong.

Qlic's avatar
Level 18

At least that gives me a response:

ErrorException in helpers.php line 671: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
veve286's avatar

$userId=Auth::user( )->id; $student=Student::where('user_id',$userId )->first( ); $student->update( $request->all( ) );

Qlic's avatar
Level 18

Your last code makes it go back to old behaviour, reload without any notice or storage.

veve286's avatar

if (Auth::user()->student === null) { Student::create($request->all() + ['user_id' => Auth::user()->id]); } else { $student = Auth::user()->student; $student->fill($request->all()); $student->save(); }

check this . U cant retrieve Auth::user()->student like this. u can only retrieve user data. this if else make u loading page without updating data.

Next

Please or to participate in this conversation.