Laravel: Difference between revisions

From Network Security Wiki
Content added Content deleted
 
(34 intermediate revisions by the same user not shown)
Line 1: Line 1:
[[Category:Scripting]]
__TOC__
<br />


= Installation =
= Installation =

Install Dependencies:
sudo apt install php7.3 apache2 php7.3-cli php7.3-sqlite3 php-xml php7.0-mysql
sudo a2enmod rewrite
sudo systemctl restart apache2

Enable below extension:
sudo nano /etc/php/7.3/apache2/php.ini
extension=pdo_mysql.so

Install Composer:
sudo apt install composer
sudo apt install composer

Check Version:
php artisan --version


Creating a project named 'code':
Creating a project named 'code':
composer create-project --prefer-dist laravel/laravel code
composer create-project --prefer-dist laravel/laravel hello
cd hello
cp .env.example .env
cp .env.example .env
php artisan key:generate
php artisan key:generate
sudo chmod -R 777 storage/
sudo chmod -R 777 storage/


Tesing output:
Testing output:
php artisan serve --host 0.0.0.0 --port 8082
php artisan serve --host 0.0.0.0 --port 8082


Edit hosts file:
Else
sudo nano /etc/hosts
192.168.1.35 hello.dev


Create a new apache conf file:
sudo nano /etc/apache2/sites-available/laravel.conf
sudo nano /etc/apache2/sites-available/laravel.conf

<pre>
<pre>
<VirtualHost *:8082>
<VirtualHost *:80>
ServerName localhost
ServerName hello.dev


ServerAdmin webmaster@localhost
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/code/public
DocumentRoot /var/www/html/hello/public


<Directory /var/www/html/code/public>
<Directory /var/www/html/hello/public>
AllowOverride All
AllowOverride All
</Directory>
</Directory>
Line 31: Line 55:


sudo nano /etc/apache2/ports.conf
sudo nano /etc/apache2/ports.conf
Listen 8082
Listen 80


sudo a2ensite laravel.conf
sudo a2ensite laravel.conf
sudo service apache2 restart
sudo service apache2 restart

The site should be available now at:
http://hello.dev/


= Auth =
= Auth =


Enable Authentication
Enable Authentication
composer require laravel/ui
php artisan make:auth
php artisan ui vue --auth

php artisan migrate

=DB access=

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

create database homestead;
grant all privileges on homestead.* to homestead@localhost identified by 'secret';


=Site Creation=
=Site Creation=


==ROUTES==
==Routes==

cd routes/
sudo nano web.php


cd routes/
sudo nano web.php
<pre>
Route::get('contact', function () {
Route::get('contact', function () {
return 'Hello from Aman';
return 'Hello from Aman';
});
});



Route::get('contact/{category}', function ($category) {
Route::get('contact/{category}', function ($category) {
return 'Hello from '.$category. ' Aman';
return 'Hello from '.$category. ' Aman';
});
});
</pre>


Check resulting pages:
http://192.168.1.35/hello/public/contact/
http://192.168.1.35/hello/public/contact/Test


==Views==
access page:
http://192.168.1.35/hello/public/contact/
http://192.168.1.35/hello/public/contact/Test


Create a new View file:
cd ../resources/views/
sudo touch master.blade.php
sudo nano master.blade.php


Paste below contents:
==VIEWS==
<pre>

cd ../resources/views/
aman@ubuntu:/var/www/html/hello/resources/views$ ls
welcome.blade.php
aman@ubuntu:/var/www/html/hello/resources/views$ sudo touch master.blade.php

<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<html lang="en">
Line 113: Line 128:
</div>
</div>
</nav>
</nav>
<!-- Online Links -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >


<div class="container">
<div class="container">
Line 122: Line 133:
</div>
</div>


<!-- Online Links -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >


</body>
</body>
</html>
</html>
</pre>




Edit Routes for this file:
cd ../../routes/
sudo nano web.php


<pre>
cd ../../routes/
aman@ubuntu:/var/www/html/hello/routes$
aman@ubuntu:/var/www/html/hello/routes$ ls
api.php channels.php console.php web.php
aman@ubuntu:/var/www/html/hello/routes$
aman@ubuntu:/var/www/html/hello/routes$ sudo nano web.php


Route::get('/home', function () {
Route::get('/home', function () {
return view('home');
return view('home');
Line 147: Line 159:
return view('new');
return view('new');
});
});



Route::get('/edit', function () {
Route::get('/edit', function () {
return view('edit');
return view('edit');
});
});
</pre>


Create above defined VIEW page:
cd ../resources/views/
sudo touch view.blade.php
sudo nano view.blade.php


Paste below contents:
<pre>
@extends('master')


@section('content')


VIEW all content goes here
cd ../resources/views/
aman@ubuntu:/var/www/html/hello/resources/views$ sudo nano
master.blade.php welcome.blade.php
aman@ubuntu:/var/www/html/hello/resources/views$ sudo touch view.blade.php
aman@ubuntu:/var/www/html/hello/resources/views$
aman@ubuntu:/var/www/html/hello/resources/views$ sudo nano view.blade.php


@endsection
</pre>

Similarly create HOME page:
sudo nano home.blade.php
<pre>
@extends('master')
@extends('master')


@section('content')
@section('content')


VIEW all content goes here
HOME all content goes here


@endsection
@endsection
</pre>


Similarly create NEW page:
sudo nano new.blade.php
<pre>
@extends('master')


@section('content')
sudo cp view.blade.php home.blade.php


NEW all content goes here

@endsection
</pre>

Similarly create EDIT page:
sudo nano edit.blade.php
<pre>
@extends('master')
@extends('master')


@section('content')
@section('content')


HOME all content goes here
EDIT all content goes here


@endsection
@endsection
</pre>


Test above page:
sudo cp view.blade.php new.blade.php
http://192.168.1.35/hello/public/home
~
sudo cp view.blade.php edit.blade.php
~


==CONTROLLERS==
==Controller==
Routes page can have URLS but this is for small Apps only
*Routes page can call URLs but this is for small applications only.
for Industrial ones, use Controllers
*For industrial applications, use Controllers.


Create a Controller:
sudo php artisan make:controller RecordController
sudo php artisan make:controller RecordController


Edit the above generated file:
cd app/Http/Controllers/
sudo nano RecordController.php


Append below contents:
cd app/Http/Controllers/
<pre>
sudo nano RecordController.php

class RecordController extends Controller
class RecordController extends Controller
{
{
Line 214: Line 250:
}
}
}
}
</pre>


Update the Routes file to use above controllers:
cd ../../routes/
sudo nano web.php


Append below content:
cd ../../routes/
<pre>
aman@ubuntu:/var/www/html/hello/routes$ sudo nano web.php


Route::get('/view', 'RecordController@showAll');
Route::get('/view', 'RecordController@showAll');


Line 225: Line 263:


Route::get('/edit', 'RecordController@showEdit');
Route::get('/edit', 'RecordController@showEdit');
</pre>


==Database==


*Easy to create & manage tables with Migrations in large environments.


Create a new DB 'hello' using phpmyadmin or below SQL Query:
==DATABASE==


Create new DB: hello
create database hello;
grant all privileges on hello.* to aman@localhost identified by 'pwd@123';


Update the ENV file with this information:
sudo nano .env
sudo nano .env


DB_CONNECTION=mysql
~add DB credentials
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hello
DB_USERNAME=aman
DB_PASSWORD=pwd@123




Create a DB table using Artisan:
Create a DB table using Artisan:


sudo php artisan make:migration create_records_table
sudo php artisan make:migration create_records_table
Created Migration: 2017_09_19_190352_create_records_table
''Created Migration: 2017_09_19_190352_create_records_table''


File is created under below location:
cd database/migrations/ && ls
''2017_09_19_190352_create_records_table.php''


Edit this file with below DB Table information:

sudo nano 2017_09_19_190352_create_records_table.php
cd database/migrations/
<pre>
aman@ubuntu:/var/www/html/hello/database/migrations$ ls
2017_09_19_190352_create_records_table.php

Easy to create tables with Migrations
Easy to manage them in large environments,


sudo nano 2017_09_19_190352_create_records_table.php

public function up()
public function up()
{
{
Line 265: Line 308:
$table->timestamps();
$table->timestamps();
});
});

}
}


/**
* Reverse the migrations.
*
* @return void
*/
public function down()
public function down()
{
{
Schema::dropIfExists('records');
Schema::dropIfExists('records');
}
}
</pre>


Create the Tables:
sudo php artisan migrate


You can confirm the Tables created in phpmyadmin.
sudo php artisan migrate


==Eloquent==


Create a model named Record
==ELOQUENT==
sudo php artisan make:model Record


cd app/
sudo php artisan make:model Record
sudo nano Record.php

cd app/


sudo nano Record.php


Add below information
<pre>
class Record extends Model
class Record extends Model
{
{
Line 297: Line 337:


}
}
</pre>


To Feed test data using Seeding, create seed file:


sudo php artisan make:seeder RecordsTableSeeder
Feed test data using Seeding:


cd database/seeds/
create seed file:
sudo nano RecordsTableSeeder.php

sudo php artisan make:seeder RecordsTableSeeder


cd database/seeds/
aman@ubuntu:/var/www/html/hello/database/seeds$ sudo nano RecordsTableSeeder.php


Append below information:
<pre>
use App\Record; //to import records.php file
use App\Record; //to import records.php file


Line 330: Line 369:
}
}
}
}
</pre>


Edit the Databse seeder file:
sudo nano DatabaseSeeder.php


<pre>


sudo nano DatabaseSeeder.php


use App\Record;
use App\Record;


Line 347: Line 385:


}
}
</pre>

Now seed the file with dummy data:
sudo php artisan db:seed
''Seeding: RecordsTableSeeder''

You will be able to see this dummy data in phpmyadmin now.

==View DB contents==

*Check all/Debug output from DB for troubleshooting:
sudo nano app/Http/Controllers/RecordController.php
Append below code into relevant sections:
<pre>
use App\Record;

class RecordController extends Controller
{
public function showAll()
{
// return view('view');
dd(Record::all()) ;
}
</pre>

Check the View page, you will find all information there
http://hello.dev/view


*Getting specific information from DB:

<pre>
class RecordController extends Controller
{
public function showAll()
{
$records=Record::all();
return view('view')->with('records',$records);
// dd(Record::all()) ;
}
</pre>


sudo nano resources/views/view.blade.php
<pre>
@extends('master')

@section('content')

<div class="container-fluid">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">All Available Aliens </h3>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-stripped table-bordered">
<thread>
<tr>
<th>Country</th>
<th>City</th>
<th>Dates</th>
<th>No of Aliens</th>
<th>Color of Aliens</th>
</tr>
</thread>
<tbody>
@foreach($records as $key=>$record)
<tr>
<td>{{$record->country}}</td>
<td>{{$record->city}}</td>
<td>{{$record->date}}</td>
<td>{{$record->no_of_aliens}}</td>
<td>{{$record->color_of_aliens}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>


@endsection
</pre>

Check the View page, you will find useful information in a table here:
http://hello.dev/view

==Entering Data==

sudo nano resources/views/new.blade.php

<pre>
@extends('master')

@section('content')

<div class="container-fluid">
<div class="panel panel-default">

<div class="panel-heading">
<h3 class="panel-title">Report New Aliens</h3>
</div>
<div class="panel-body">
<form role="form" method="POST" action="{{url('/info')}}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">

<div class="form-group">
<label class="col-md-3 control-label">Country:</label>
<div class="col-md-9">
<input type="text" class="form-control" name='country' value="{{ old('country') }}"/></br>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">City:</label>
<div class="col-md-9">
<input type="text" class="form-control" name='city' value="{{ old('city') }}"/></br>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Date:</label>
<div class="col-md-9">
<input type="text" class="form-control" name='date' value="{{ old('date') }}"/></br>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">No of Aliens:</label>
<div class="col-md-9">
<input type="text" class="form-control" name='no_of_aliens' value="{{ old('no_of_aliens') }}"/></br>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Color of Aliens:</label>
<div class="col-md-9">
<input type="text" class="form-control" name='color_of_aliens' value="{{ old('color_of_aliens') }}"/></br>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-6">
<button type="submit" class="btn btn-success btn-block" value='Submit'>Submit</button>
</div>
</div>

</form>
</div>
</div>
</div>

@endsection
</pre>


sudo nano routes/web.php
<pre>
Route::post('/info', 'RecordController@store');
</pre>


Now you can see the Form Page:
http://hello.dev/new

==Enable store Function to send data to DB==


sudo nano app/Http/Controllers/RecordController.php

<pre>
public function store(Request $request)
{
$Record=new Record;

$Record->country=$request->get('country');
$Record->city=$request->get('city');
$Record->date=$request->get('date');
$Record->no_of_aliens=$request->get('no_of_aliens');
$Record->color_of_aliens=$request->get('color_of_aliens');

$Record->save();

return redirect()->back(); // this will rediect back to the same page to enter more data
}
</pre>

Now you can enter the data from Form Page which will be saved into DB:
http://hello.dev/new

Data entered will be visible here:
http://hello.dev/view

==Showing Messages==
sudo nano app/Http/Controllers/RecordController.php

Inside this function:
public function store(Request $request)
Below this file:
$Record->save();
Insert:
$request->session()->flash('flash_message','New record added successfully');


To show above errors/messages:
sudo nano resources/views/master.blade.php

Before this section:
<pre>
<div class="container">
@yield('content')
</pre>

Paste:
<pre>
@if(Session::has('flash_message'))
<div class="alert alert-success">
{{ Session::get('flash_message') }}
</div>
@endif

@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some errors with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
</pre>

==Data Validation using Laravel Request==
Generate a request file:
cd /var/www/html/hello
sudo php artisan make:request RecordDataRequest


Edit this file:
sudo nano app/Http/Requests/RecordDataRequest.php

<pre>
public function authorize()
{
return true;
}


public function rules()
{
return [
'country'=>'required',
'city'=>'required',
];
}
</pre>

Edit this file:
sudo nano app/Http/Controllers/RecordController.php
Append:
use App\Http\Requests\RecordDataRequest;


Edit this file:
sudo nano app/Http/Controllers/RecordController.php

Change:
public function store(Request $request)
To:
public function store(RecordDataRequest $request)

Code to display all error messages is already added in earlier section.


<br />
;References
<references/>
<br />
<br />
<br />




{{DISQUS}}
aman@ubuntu:/var/www/html/hello$ sudo php artisan db:seed
Seeding: RecordsTableSeeder

Latest revision as of 17:17, 25 March 2020



Installation

Install Dependencies:

sudo apt install php7.3 apache2 php7.3-cli php7.3-sqlite3 php-xml php7.0-mysql
sudo a2enmod rewrite
sudo systemctl restart apache2

Enable below extension:

sudo nano /etc/php/7.3/apache2/php.ini
extension=pdo_mysql.so

Install Composer:

sudo apt install composer

Check Version:

php artisan --version

Creating a project named 'code':

composer create-project --prefer-dist laravel/laravel hello
cd hello
cp .env.example .env
php artisan key:generate
sudo chmod -R 777 storage/

Testing output:

php artisan serve --host 0.0.0.0 --port 8082

Edit hosts file:

sudo nano /etc/hosts
192.168.1.35	hello.dev

Create a new apache conf file:

sudo nano /etc/apache2/sites-available/laravel.conf
<VirtualHost *:80>
    ServerName hello.dev

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/hello/public

    <Directory /var/www/html/hello/public>
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
sudo nano /etc/apache2/ports.conf
Listen 80
sudo a2ensite laravel.conf
sudo service apache2 restart

The site should be available now at:

http://hello.dev/

Auth

Enable Authentication

composer require laravel/ui
php artisan ui vue --auth
php artisan migrate

Site Creation

Routes

cd routes/
sudo nano web.php
Route::get('contact', function () {
    return 'Hello from Aman';
});

Route::get('contact/{category}', function ($category) {
    return 'Hello from '.$category. ' Aman';
});

Check resulting pages:

http://192.168.1.35/hello/public/contact/
http://192.168.1.35/hello/public/contact/Test

Views

Create a new View file:

cd ../resources/views/
sudo touch master.blade.php
sudo nano master.blade.php

Paste below contents:

<!DOCTYPE html>
<html lang="en">
<head>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE-edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>HELLO</title>

</head>
<body>

	<nav class="navbar navbar-inverse">
	<div class="container-fluid">

	 <div class="navbar-header">
		<a class="navbar-brand" href="{{url('/home')}}">Home</a>
	 </div>

	 <div>
		<ul class="nav navbar-nav">
		<li><a href="{{url('/view')}}">View All</a></li>
		<li><a href="{{url('/new')}}">Add New</a></li>
		<li><a href="{{url('/edit')}}">Edit/Delete</a></li>
		</ul>
	 </div>

	</div>
	</nav>

	<div class="container">
	  @yield('content')
	</div>

<!-- Online Links -->
	<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >

</body>
</html>


Edit Routes for this file:

cd ../../routes/
sudo nano web.php 
Route::get('/home', function () {
    return view('home');
});

Route::get('/view', function () {
    return view('view');
});

Route::get('/new', function () {
    return view('new');
});

Route::get('/edit', function () {
    return view('edit');
});

Create above defined VIEW page:

cd ../resources/views/
sudo touch view.blade.php 
sudo nano view.blade.php

Paste below contents:

@extends('master')

@section('content')

VIEW all content goes here

@endsection

Similarly create HOME page:

sudo nano home.blade.php
@extends('master')

@section('content')

HOME all content goes here

@endsection

Similarly create NEW page:

sudo nano new.blade.php
@extends('master')

@section('content')

NEW all content goes here

@endsection

Similarly create EDIT page:

sudo nano edit.blade.php
@extends('master')

@section('content')

EDIT all content goes here

@endsection

Test above page:

http://192.168.1.35/hello/public/home

Controller

  • Routes page can call URLs but this is for small applications only.
  • For industrial applications, use Controllers.

Create a Controller:

sudo php artisan make:controller RecordController

Edit the above generated file:

cd app/Http/Controllers/
sudo nano RecordController.php 

Append below contents:

class RecordController extends Controller
{
  public function showAll()
        {
                return view('view');
        }

  public function showNew()
        {
                return view('new');
        }

  public function showEdit()
        {
                return view('edit');
        }
}

Update the Routes file to use above controllers:

cd ../../routes/
sudo nano web.php

Append below content:

Route::get('/view', 'RecordController@showAll');

Route::get('/new', 'RecordController@showNew');

Route::get('/edit', 'RecordController@showEdit');

Database

  • Easy to create & manage tables with Migrations in large environments.

Create a new DB 'hello' using phpmyadmin or below SQL Query:

create database hello;
grant all privileges on hello.* to aman@localhost identified by 'pwd@123';

Update the ENV file with this information:

sudo nano .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hello
DB_USERNAME=aman
DB_PASSWORD=pwd@123


Create a DB table using Artisan:

sudo php artisan make:migration create_records_table
Created Migration: 2017_09_19_190352_create_records_table

File is created under below location:

cd database/migrations/ && ls
2017_09_19_190352_create_records_table.php

Edit this file with below DB Table information:

sudo nano 2017_09_19_190352_create_records_table.php
    public function up()
    {
        Schema::create('records', function (Blueprint $table) {
            $table->increments('id');
            $table->string('country');
            $table->string('city');
            $table->string('date');
            $table->string('no_of_aliens');
            $table->string('color_of_aliens');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('records');
    }

Create the Tables:

sudo php artisan migrate

You can confirm the Tables created in phpmyadmin.

Eloquent

Create a model named Record

sudo php artisan make:model Record 
cd app/
sudo nano Record.php

Add below information

class Record extends Model
{
    protected $table='records';
    protected $fillable=['id','country','city','date','no_of_aliens','color_of_aliens'];

}

To Feed test data using Seeding, create seed file:

sudo php artisan make:seeder RecordsTableSeeder
cd database/seeds/
sudo nano RecordsTableSeeder.php 

Append below information:

use App\Record;    //to import records.php file

class RecordsTableSeeder extends Seeder
{
  public function run()
    {
       for ($i=0; $i<20; $i++)
        {
           Record::create
            (
                [
                   'country' => "country$i",
                   'city' => "city$i",
                   'date' => "date$i",
                   'no_of_aliens' => "no_of_aliens$i",
                   'color_of_aliens' => "color_of_aliens$i"
                ]
            );
        }
    }
}

Edit the Databse seeder file:

sudo nano DatabaseSeeder.php 
use App\Record;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call('RecordsTableSeeder');
    }

}

Now seed the file with dummy data:

sudo php artisan db:seed
Seeding: RecordsTableSeeder

You will be able to see this dummy data in phpmyadmin now.

View DB contents

  • Check all/Debug output from DB for troubleshooting:
sudo nano app/Http/Controllers/RecordController.php 

Append below code into relevant sections:

use App\Record;

class RecordController extends Controller
{
  public function showAll()
        {
        //      return view('view');
                dd(Record::all()) ;
        }

Check the View page, you will find all information there

http://hello.dev/view


  • Getting specific information from DB:
class RecordController extends Controller
{
  public function showAll()
        {
                $records=Record::all();
                return view('view')->with('records',$records);
        //      dd(Record::all()) ;
        }


sudo nano resources/views/view.blade.php
@extends('master')

@section('content')

	<div class="container-fluid">
		<div class="panel panel-default">
			<div class="panel-heading">
				<h3 class="panel-title">All Available Aliens </h3>
			</div>
			<div class="panel-body">
			   <div class="table-responsive">
			      <table class="table table-stripped table-bordered">
			         <thread>
				    <tr>
				       <th>Country</th>
				       <th>City</th>
				       <th>Dates</th>
				       <th>No of Aliens</th>
				       <th>Color of Aliens</th>
				    </tr>
				 </thread>
				 <tbody>
					@foreach($records as $key=>$record)
					 <tr>
					   <td>{{$record->country}}</td>
					   <td>{{$record->city}}</td>
					   <td>{{$record->date}}</td>
					   <td>{{$record->no_of_aliens}}</td>
					   <td>{{$record->color_of_aliens}}</td>
					 </tr>
					@endforeach
				 </tbody>
				</table>
			   </div>
			</div>
		  </div>
		</div>


@endsection

Check the View page, you will find useful information in a table here:

http://hello.dev/view

Entering Data

sudo nano resources/views/new.blade.php
@extends('master')

@section('content')

    <div class="container-fluid">
	<div class="panel panel-default">

	   <div class="panel-heading">
		<h3 class="panel-title">Report New Aliens</h3>
	   </div>
	   <div class="panel-body">
	    <form role="form" method="POST" action="{{url('/info')}}">
	    <input type="hidden" name="_token" value="{{ csrf_token() }}">

			<div class="form-group">
			<label class="col-md-3 control-label">Country:</label>
			<div class="col-md-9">
				<input type="text" class="form-control" name='country' value="{{ old('country') }}"/></br>
			</div>
			</div>
			<div class="form-group">
			<label class="col-md-3 control-label">City:</label>
			<div class="col-md-9">
				<input type="text" class="form-control" name='city' value="{{ old('city') }}"/></br>
			</div>
			</div>
			<div class="form-group">
			<label class="col-md-3 control-label">Date:</label>
			<div class="col-md-9">
				<input type="text" class="form-control" name='date' value="{{ old('date') }}"/></br>
			</div>
			</div>
			<div class="form-group">
			<label class="col-md-3 control-label">No of Aliens:</label>
			<div class="col-md-9">
				<input type="text" class="form-control" name='no_of_aliens' value="{{ old('no_of_aliens') }}"/></br>
			</div>
			</div>
			<div class="form-group">
			<label class="col-md-3 control-label">Color of Aliens:</label>
			<div class="col-md-9">
				<input type="text" class="form-control" name='color_of_aliens' value="{{ old('color_of_aliens') }}"/></br>
			</div>
			</div>
                        <div class="form-group">
                        <div class="col-md-6 col-md-offset-6">
                                <button type="submit" class="btn btn-success btn-block" value='Submit'>Submit</button>
                        </div>
                        </div>

	    </form>
	   </div>
	</div>
    </div>

@endsection


sudo nano routes/web.php
 Route::post('/info', 'RecordController@store');


Now you can see the Form Page:

http://hello.dev/new

Enable store Function to send data to DB

sudo nano app/Http/Controllers/RecordController.php
  public function store(Request $request)
        {
                $Record=new Record;

		$Record->country=$request->get('country');
		$Record->city=$request->get('city');
		$Record->date=$request->get('date');
		$Record->no_of_aliens=$request->get('no_of_aliens');
		$Record->color_of_aliens=$request->get('color_of_aliens');

		$Record->save();

		return redirect()->back(); // this will rediect back to the same page to enter more data
        }

Now you can enter the data from Form Page which will be saved into DB:

http://hello.dev/new

Data entered will be visible here:

http://hello.dev/view

Showing Messages

sudo nano app/Http/Controllers/RecordController.php

Inside this function:

 public function store(Request $request)

Below this file:

$Record->save();

Insert:

$request->session()->flash('flash_message','New record added successfully');


To show above errors/messages:

sudo nano resources/views/master.blade.php

Before this section:

        <div class="container">
          @yield('content')

Paste:

          @if(Session::has('flash_message'))
                <div class="alert alert-success">
                    {{ Session::get('flash_message') }}
                </div>
          @endif

          @if (count($errors) > 0)
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some errors with your input.<br><br>
                <ul>
                  @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                  @endforeach
                </ul>
            </div>
          @endif

Data Validation using Laravel Request

Generate a request file:

cd /var/www/html/hello
sudo php artisan make:request RecordDataRequest


Edit this file:

sudo nano app/Http/Requests/RecordDataRequest.php
    public function authorize()
    {
        return true;
    }


    public function rules()
    {
        return [
            'country'=>'required',
            'city'=>'required',
        ];
    }

Edit this file:

sudo nano app/Http/Controllers/RecordController.php

Append:

use App\Http\Requests\RecordDataRequest;


Edit this file:

sudo nano app/Http/Controllers/RecordController.php

Change:

public function store(Request $request)

To:

public function store(RecordDataRequest $request)

Code to display all error messages is already added in earlier section.



References





{{#widget:DISQUS |id=networkm |uniqid=Laravel |url=https://aman.awiki.org/wiki/Laravel }}