Skip to content

Instantly share code, notes, and snippets.

@deividaspetraitis
Last active September 10, 2020 08:24
Show Gist options
  • Save deividaspetraitis/d7c646e04ac3fbd0804e7a2f41158cda to your computer and use it in GitHub Desktop.
Save deividaspetraitis/d7c646e04ac3fbd0804e7a2f41158cda to your computer and use it in GitHub Desktop.
How to bypass mass assignment protection in laravel?
<?php
class Article extends \Illuminate\Database\Eloquent\Model
{
/**
* All available model properties ( DB fields )
*
* @var array $schema
*/
protected $schema = [
0 => 'id',
1 => "title",
2 => "body",
3 => "state"
];
/**
* The attributes that are mass assignable.
*
* @var array $fillable
*/
protected $fillable = [
0 => "title",
1 => "body"
];
}
// ------- Case 1 ---------
// When user creates article
$article = Article::create(Input::all());
// ------- Case 2 ---------
// Internal application case ( for example import case )
// I want to bypass $fillable and be able to set ID manually
Article::unguard();
$article = Article::create(['id' => 1, 'title' => 'title', 'body' => 'body']);
Article::reguard();
// ------- Case 2 ---------
// Allow user be able fill title and body attributes
// And internally set state attribute as active
$article = Article::create(Input::all());
// ------- Case 3 ---------
// Allow user be able fill title and body attributes
// This user is administrator and allow him fill state attribute as well?
if (user() == 'admin') {
$article->fillable[] = "state"; // is it a right way to allow him fill state attribute?
}
$article = Article::create(Input::all());
@sense-it-gmbh
Copy link

Helped a lot! Thanks! Worked on Laravel 7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment