Jack
Jack

Reputation: 9784

Laravel's Model::create() function isn't setting a custom field value

Laravel newbie here, sorry if this is painfully obvious but I've been stuck on it for ages!

Objective: To mass-assign a Quote::create() database insertion with the full values from the form, plus set the User ID to the currently logged in user.

Problem: The user_id column is never written to the database. Every other column is, but user_id remains as 0.

I have of course tried adding user_id to the $fillable array, but I don't want it to be user-fillable - I want it to be set by Laravel's Auth::id() function.

Any ideas why this won't get stored? Is it because the $quote->create() function doesn't factor in previously set data and just takes its parameter as everything to be saved? If so how do I do this?

Here's my controller's store() function:

/**
     * Stores a created quote in the database
     *
     * @param QuoteRequest $request
     *
     */
    public function store(QuoteRequest $request)
    {
        // This method will only get fired if QuoteRequest passes
        $quote = new Quote;
        $quote->user_id = Auth::id();
        $quote->create($request->all());

        echo 'Job done';
    }

Here's my Quote model:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;

class Quote extends Model {

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'quote_person',
        'quote_value',
        'quote_date'
    ];

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

    /*
     * Request/User many-to-one relationship
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /*
     * Belongs to current User scope
     */
    public function scopeMine($query)
    {
        return $query->where('user_id', Auth::id());
    }

}

Upvotes: 3

Views: 4184

Answers (2)

ceejayoz
ceejayoz

Reputation: 179994

The create function is considered mass assignment and is thusly affected by $fillable / $guarded. It's also a static function, so $quote->create() is making an entirely new Eloquent instance - that's why your manually assigned user_id is lost.

You can use Model::unguard() to temporarily turn off the protection.

Upvotes: 3

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13325

Try this and see if it works.

public function store(QuoteRequest $request)
{
    // This method will only get fired if QuoteRequest passes
    $quote = new Quote;
    $quote->fill($request->all());
    $quote->user_id = Auth::id();
    $quote->save();

    echo 'Job done';
}

Upvotes: 7

Related Questions