Laravel Model :: create () function does not set custom field value

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

Purpose : To bulk assign a database insert Quote::create()

with full values ​​from a form plus setting a user id for the current user.

Problem . The column is user_id

never written to the database. Each column is there but user_id

remains 0.

I tried adding user_id

to the array of course, $fillable

but I don't want it to be populated by the user - I want it to be set by a Laravel function Auth::id()

.

Any ideas why this won't be saved? Is it because the function $quote->create()

doesn't take into account the previously set data and just takes its parameter as all that needs to be saved? If so, how do you do it?

Here's my control function store()

:

/**
     * 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 model Quote

:

<?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 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());
    }

}

      

+3


source to share


2 answers


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';
}

      

+7


source


The function create

is considered a mass assignment and is affected by $fillable

/ $guarded

. It's also a static function, so it $quote->create()

creates a completely new Eloquent instance - so your lost one is manually user_id

lost.



You can use Model::unguard()

to temporarily disable protection.

+3


source







All Articles