Muaath Alhaddad
Muaath Alhaddad

Reputation: 361

How many ways exist to Store data from laravel form to database?

I am new to Laravel, as far as I know, there three ways to store data form into DB, please correct me if I am wrong:

First way: instantiating an object from the model

$tutor = new Tutor();
$tutor ->name = $request->name;
// in some tutorials they use: 
// $tutor->name = request('name');
// what is the difference?
$tutor ->salary = $request->salary;
$tutor->save();

Second way: converting the object into an array

$tutor = array([
  'name'   => $request->name, // vs 'name' => $request->input('name'), what is the difference?
  'salary' => $request->salary
]);
$tutor->save(); // Do I need to save here?

Third way: using a global helper method

$tutor = Tutor::create($request->all());

Upvotes: 1

Views: 563

Answers (1)

Salim Djerbouh
Salim Djerbouh

Reputation: 11034

difference between request('name') and $request('name');

request() is a global helper function that can be used anywhere to access the HTTP request object

$request is the parameter passed to the controller function which means THE request passed to this controller, would be useful when validating data via form request classes

Do I need to save data here?

Second way shouldn't work at all as written, you may mean

$tutor = new Tutor([
  'name'   => $request->name,
  'salary' => $request->salary
]);
$tutor->save();

which is manually stripping out additional form posted data, it's no different from

$tutor = new Tutor();
$tutor->create(request()->only(['name', 'salary']));

$request->name vs 'name' => $request->input('name') what is the difference?

using the input method means grab the name parameter from a user input no matter what HTTP method was used GET or POST or to quote the docs

Retrieving An Input Value

Using a few simple methods, you may access all of the user input from your Illuminate\Http\Request instance without worrying about which HTTP verb was used for the request. Regardless of the HTTP verb, the input method may be used to retrieve user input:

$name = $request->input('name');

Third way uses mass assignment from everything posted in the request including what you didn't intend from malicious users (hackers)

Avoid it at all costs

Hope this helps

Upvotes: 1

Related Questions