Select Query in Laravel using Eloquent ORM
Create Controller
Open new terminal and run this command to create controller
php artisan make:controller customerController
Configure routes
Go to routes>web.php
use App\Http\Controllers\customerController;
Route::get('/customer', [customerController::class, 'index']);
Route::post('/customer', [customerController::class, 'store']);
Route::get('/customer/view', [customerController::class, 'view']);
index is a function which return customer page and store is a function which store the data submitted through form. view is a function which fetch and view the data to the page, as given below.
App>Http>Controllers:
";
print_r($request->all());
$customers = new Customers;
$customers->name = $request['name'];
$customers->email = $request['email'];
$customers->password = md5($request['password']);
$customers->city = $request['city'];
$customers->state = $request['state'];
$customers->address = $request['address'];
$customers->gender = $request['gender'];
$customers->dob = $request['dob'];
$customers->save();
return redirect('/customer/view');
}
public function view(){
$customers = Customers::all();
// echo "";
// print_r($customers->toArray());
// echo "";
$data = compact('customers');
return view('customer-view')->with($data);
}
}
Above code is use to insert data. $customers->name is a database name and $request['name']; is a name which is present in input tag.
In the view function Customers::all() collect the data, the compact function convert it into the array and with sends it to customer.blade.php
Note - Target table using - use App\Models\Customers; because table name is customers in the database>migration>customers_table.
App>Models>Customers.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customers extends Model
{
use HasFactory;
protected $table = "customers";
protected $primaryKey = "customer_id";
}
The Table is given below
Create a file inside resources>views>customer-view.blade.php
@foreach ($customers as $customer)
@endforeach
Name
Email
Gender
State
City
DOB
Status
{{$customer->name}}
{{$customer->email}}
@if ($customer->gender == "M")
Male
@elseif($customer->gender == "F")
Female
@else
Other
@endif
{{$customer->state}}
{{$customer->city}}
{{$customer->dob}}
@if ($customer->status == "1")
Active
@else
Inactive
@endif
resources>views>customer.blade.php The Form is given below Create a file inside
Customer Registration
Comments
Post a Comment