Reputation: 282
please help me i'm using Laravel 5.4 and i want save on databese from model function.
This is my controller
public function addStockSizes(Request $request)
{
if ($request->isMethod('post')) {
$this->validate($request, [
'size' => 'required',
]);
$data['size'] = $request->input('size');
$data['netSize'] = $request->input('net_size');
$data['mouseText'] = $request->input('mouse_text');
Stock_size::createSize($data);
return redirect()->back()->with('success', true)->with('message',
'Size is successfully added');
} else {
$sizes = Stock::all();
return view('admin.StockSize.addStockSizes', compact('sizes'));
}
}
And this is my function in model
public static function createSize($data)
{
$size = $data['size'];
$netSize = $data['netSize'];
$mouseText = $data['mouseText'];
$model = new self();
$model->size = $size;
$model->net_size = $netSize;
$model->mouse_text = $mouseText;
$model->save();
}
Upvotes: 1
Views: 126
Reputation: 33186
You can use the create
function on an Eloquent model. This function expects an associative array with the data for the database.
Stock_size::create($request->only(['size', 'net_size', 'mouse_text']));
Keep in mind that you might get a MassAssignmentException
because model properties are guarded against this by default. This can be fixed by adding the fields that are inserted to the $fillable
array of your model:
protected $fillable = ['size', 'net_size', 'mouse_text'];
Upvotes: 2