Last active
September 10, 2020 08:24
-
-
Save deividaspetraitis/d7c646e04ac3fbd0804e7a2f41158cda to your computer and use it in GitHub Desktop.
How to bypass mass assignment protection in laravel?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Helped a lot! Thanks! Worked on Laravel 7.