How to store data in laravel
In Laravel We are using Eloquent then we don’t only need to retrieve models from the database. We also need to insert new records. Eloquent makes it simple. To save a new record into the database, you should create a new model instance and set attributes on the model. Then, use the save
method on the model instance:
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Http\Client\ConnectionException; use Illuminate\Support\Facades\DB; use App\Models\Lead; class Leads extends Controller { public function addform(Request $req) { $lead = newLead; $lead->name = $req->user; $lead->email = $req->email; $lead->mobile = $req->mobile; $lead->msg = $req->msg; $lead->save(); return redirect ('contact'); } }
In this given example, we assign the user, email, mobile, msg
field from the incoming HTTP request to the user
attribute of the App\Models\Lead
model instance. When we call the save
method, a record will be inserted into the database. The model’s created_at
and updated_at
timestamps will automatically be set when the save
method is called, so there is no need to set them manually.
Alternatively, you may use the create
method to “save” a new model using a single PHP statement. The inserted model instance will be returned to you by the create
method:
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Lead extends Model { useHasFactory; public$timestamps = false; }
However, before using the create
method, you will need to specify either a fillable
or guarded
property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default.