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=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Let's create our first model object.

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
Above command will create a Model object named Guide and a migration file. Open the migration file database/migrations/2020_09_06_012809_create_guides_table.php. You can see the file name in the success message, while creating the model. It will have the basic skeleton, and look for the up() function, which helps us to create the table.

public function up()
{
Schema::create('guides', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
Update the function with the below code.
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();
});
}
We have added first_name, last_name, email, job_title and salary fields to the guides table. Now you can create the guide table in the database using the below artisan command.
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)
Now open our Guide Model, which will be used to interact with the guides table. The file resides inside the app folder. Open the file guide.php, it is just basic skeleton, it doesn't have anything, other than the empty class.
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'
];
}
That's all you all set now.  Now let's create a new controller named GuideController, execute the below command, from the root of the application.
c:\xampp\htdocs\curdexample>php artisan make:controller GuideController --resource
Controller created successfully.
This will create a new controller file in the following path "app/Http/Controllers/GuideController.php", which will have seven methods by default namely index(), create(), store(), show(), edit(), update() and destroy().

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');
Using the resource() static method of Route(), you can create multiple routes to expose multiple actions on the resource. This will provide some default routes which are mapped to GuideController default methods, which we need to implement. Below are the routes which are mapped to relevant methods.

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>
Now let's the form for getting the guide details. Create a new folder named "guides" inside the resources/views, and create a new file named create.blade.php, this simply represents the view "guides.create" you defined in the create function(). Update the file with the below code.
@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
Now let's create index.blade.php under "resources/views/guides", and update it with the below content.
@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

Popular posts from this blog

Method Reference in Java Streams

PHP LARAVEL Directory Structure

PHP LARAVEL - Hello World Laravel