Home > front end >  In Laravel, why can I not assign values to an Eloquent Model directly from an array?
In Laravel, why can I not assign values to an Eloquent Model directly from an array?

Time:06-28

This isn't causing any problems, I'm just totally confused by some behaviour I'm running into so would appreciate some insight.

In my Laravel application I hit an API and loop through it like so:

$response = Http::get('https://example.com/api');
$articles = $response->json();

foreach($articles as $article){
    // do stuff
}

Within the loop I then use an Eloquent model to persist some data to my database. The thing that's totally confusing me though is that if do this, it works fine:

$article_permalink = $article['permalink'];
$article_headline = $article['headline'];

$article = new Article;
$article->permalink = $article_permalink;
$article->headline = $article_headline;
$article->save();

Whereas if I just assign the values directly from my array, it doesn't work, and I receive the error below:

$article = new Article;
$article->permalink = $article['permalink'];
$article->headline = $article['headline'];
$article->save();
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'permalink' cannot be null

I receive the above error for both fields. These values absolutely are defined in all cases, and it works flawlessly simply by first assigning the array version of variable to a standard variable before insertion. What could I be missing?

Thanks

CodePudding user response:

You are overwriting your $article variable. So when you assign your model attributes $article is no longer an array but an empty Article Model Object.

Try this:

$articleModel = new Article;
$articleModel->permalink = $article['permalink'];
$articleModel->headline = $article['headline'];
$articleModel->save();

Alternatively, changes your loop to:

foreach($articles as $articleArray){
    $article = new Article;
    $article->permalink = $articleArray['permalink'];
    $article->headline = $articleArray['headline'];
    $article->save();
}

CodePudding user response:

On your model: permalink and headline should be fillable:

class Atricle extends Model
{
    protected $fillable = [
        'permalink',
        'headline',
    ];
}

  • Related