PHP LARAVEL - Simple CURD example - TUTORIAL - 1
In the post, you will learn how to create a simple LARAVEL CRUD application from scratch. Let's start with how we create a fresh project, configure DB settings and writing the necessary model and controllers to interact with DB.
In order to create a fresh installation of Laravel project, open the command prompt and type the below command. This will create a fresh project named curdexample.
composer create-project laravel/laravel curdexample
Go, to the project and open .env file, and set the DB_CONNECTION to MySQL, since we will be using the MySQL as our database for this example. Update all other details like HOST, DATABASE, USERNAME and PASSWORD.
DB_CONNECTION=mysqlLet's create our first model object.
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Laravel uses the MVC architecture to organize the application into three separate parts (Model, View and Controller). Model defines the data access layer, so let's creating the model first. Open the command prompt and type the below command from the root of the project folder.
c:\xampp\htdocs\curdexample>php artisan make:model Guide --migration
Model created successfully.
Created Migration: 2020_09_06_012809_create_guides_table
public function up()
{
Schema::create('guides', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
public function up()
{
Schema::create('guides', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('job_title');
$table->integer('salary');
$table->timestamps();
});
}
c:\xampp\htdocs\curdexample>php artisan migrate
Migrating: 2020_09_06_012809_create_guides_table
Migrated: 2020_09_06_012809_create_guides_table (0.06 seconds)
class Guide extends Model
{
//
}
Update the Guide Model, like below, you are adding fillable property, which specifies which attributes in the table should be mass-assignable (send an array to the model to directly create a new record in DB).
class Guide extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'job_title',
'salary'
];
}
c:\xampp\htdocs\curdexample>php artisan make:controller GuideController --resource
Controller created successfully.
Just update the three methods index(), create() and store(), with the below code. create() is for showing the form for creating the guide, store() will accept the form submit and create the guide in the DB, and index() to list the guides.
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$guides = Guide::all();
return view('guides.index', compact('guides')) ->with('i', 0);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('guides.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required'
]);
Guide::create($request->all());
return redirect()->route('guides.index')
->with('success','Guide created successfully.');
}
Now we have Controller part, lets setup the routes, to map the methods. Open the routes/web.php file and update it accordingly.
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::resource('guides','GuideController');
GET /guides, mapped to the index() method,
GET /guides/create, mapped to the create() method,
POST /guides, mapped to the store() method,
GET /guides/{guides} mapped to the show() method,
GET /guides/{guides}/edit mapped to the edit() method,
PUT/PATCH /guides/{guides}, mapped to the update() method,
DELETE /guides/{guides}, mapped to the delete() method.
Now let's create view files. We will create three blade files, layout file, guide create form and guide list.
Let' start with creating the layout file. Create a new file named layout.blade.php under resources/views folder, and update it with the below content. This file acts as wrapper for all other blade files.
<!DOCTYPE html>
<html>
<head>
<title>Laravel Simple CRUD Application</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
@extends('layout')
@section('content')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Add a guide</h1>
<div>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif
<form method="post" action="{{ route('guides.store') }}">
@csrf
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name"/>
</div>
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email"/>
</div>
<div class="form-group">
<label for="city">Job Title:</label>
<input type="text" class="form-control" name="job_tile"/>
</div>
<div class="form-group">
<label for="country">Salary:</label>
<input type="text" class="form-control" name="salary"/>
</div>
<button type="submit" class="btn btn-primary-outline">Add Guide</button>
</form>
</div>
</div>
</div>
@endsection
@extends('layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel Simple CRUD Example</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('guides.create') }}"> Create New Guide</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Title</th>
<th>Salary</th>
<th width="280px">Action</th>
</tr>
@foreach ($guides as $guide)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $guide->first_name }}</td>
<td>{{ $guide->email }}</td>
<td>{{ $guide->job_title }}</td>
<td>{{ $guide->salary }}</td>
<td>
<form action="{{ route('guides.destroy',$guide->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('guides.show',$guide->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('guides.edit',$guide->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endsection
Now run the application and go to http://localhost:8000/guides/create - you will see the guides form, enter the details, on successful completion, it will take you to the http://localhost:8000/guides, which will display the list of guides in the system.
That's all, we have seen how to setup application, configure the DB, creating controllers/view, how to associate them. We will see other methods in the next tutorial.
Happy Programming...!!!
Comments
Post a Comment