Read More
.
Surf to https://phpsandbox.io
Create an account e.g. using Google account.
Select Laravel version e.g. Laravel 8
Type a name e.g. lara8
In config/database.php edit as follows:
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
'default' => env('DB_CONNECTION', 'sqlite'),
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => database_path('database.sqlite'),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
php artisan migrate
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DevController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\CommonController;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
/* hello */
Route::get('/hello', function () {
return( 'hello');
});
/* auth */
Route::post('/register',[AuthController::class,'register']);
Route::post('/login',[AuthController::class,'login']);
Route::post('/me',[AuthController::class,'me'])->middleware('auth:sanctum');
/* dev */
Route::get('/init',[DevController::class,'init']);
Route::get('/table',[DevController::class,'get_table']);
Route::get('/{table}/desc',[DevController::class,'get_table_description']);
/* common */
Route::get('/{table}/record',[CommonController::class,'get_table_record']);
Route::get('/{table}/{record_where}/{field}/{value}',[CommonController::class,'get_table_record_where'])
->where(['record_where' =>'record_where|recordw']);
Route::get('/insert/{json?}',[CommonController::class,'get_insert_record']);
Route::post('/insert',[CommonController::class,'post_insert_record']);
Route::get('/update/{json?}',[CommonController::class,'get_update_record']);
Route::post('/update',[CommonController::class,'post_update_record']);
Route::get('/delete/{json?}',[CommonController::class,'get_delete_record']);
Route::post('/delete',[CommonController::class,'post_delete_record']);
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class DevController extends Controller
{
public function init(Request $request)
{
Schema::dropIfExists('staff');
if (!Schema::hasTable("staff")) {
Schema::create("staff", function (Blueprint $table) {
$table->id();
$table->string("s_name");
$table->string("s_email")->unique();
$table->string("s_dept");
$table->string("s_bran");
});
}
if (Schema::hasTable("staff")) {
DB::delete('delete from staff');
DB::insert('insert into staff (s_name,s_email,s_dept,s_bran)
values (?,?,?,?)',
['john','john@gmail.com','D1','D1B1']);
DB::insert('insert into staff (s_name,s_email,s_dept,s_bran)
values (?,?,?,?)',
['nancy','nancygmail.com','D2','D2B2']);
}
Schema::dropIfExists('dept');
if (!Schema::hasTable("dept")) {
Schema::create('dept', function (Blueprint $table) {
$table->id();
$table->string('s_code')->unique();
$table->string('s_name');
});
}
if (Schema::hasTable("dept")) {
DB::delete('delete from dept');
DB::insert('insert into dept (s_code,s_name) values (?,?)',
['D1','Department 1']);
DB::insert('insert into dept (s_code,s_name) values (?,?)',
['D2','Department 2']);
}
Schema::dropIfExists('bran');
if (!Schema::hasTable("bran")) {
Schema::create('bran', function (Blueprint $table) {
$table->id();
$table->string('s_code')->unique();
$table->string('s_dept');
$table->string('s_name');
});
}
if (Schema::hasTable("bran")) {
DB::delete('delete from bran');
DB::insert('insert into bran (s_dept,s_code,s_name)
values (?,?,?)',
['D1','D1B1','Branch 1 of D1']);
DB::insert('insert into bran (s_dept,s_code,s_name)
values (?,?,?)',
['D1','D1B2','Branch 2 of D1']);
DB::insert('insert into bran (s_dept,s_code,s_name)
values (?,?,?)',
['D2','D2B1','Branch 1 of D2']);
DB::insert('insert into bran (s_dept,s_code,s_name)
values (?,?,?)',
['D2','D2B2','Branch 2 of D2']);
}
/*create json data*/
$json_data =
'{"table":["staff","dept","bran"],"status":"init"}';
/*convert json object to php object*/
$response = json_decode($json_data);
/**/
return response()->json($response, 200);
}
public function get_table()
{
/*mysql*/
//$table_collection = DB::select('SHOW TABLES');
/*sqlite*/
$table_collection = DB::select("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");
return response()->json($table_collection, 200);
}
public function get_table_description($table)
{
$field_collection = Schema::getColumnListing($table);
return response()->json($field_collection, 200);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CommonController extends Controller
{
public function get_table_record($table)
{
$result = DB::select("select * from " . $table);
return response()->json($result, 200);
}
public function get_table_record_where($table,$recordw,$field,$value)
{
$result = DB::select('select * from ' . $table . ' where ' .
$field . ' = ' . $value);
return response()->json($result, 200);
}
public function exec_insert_record($objt_param)
{
$response = (object) ['result' => (object)[],'error' => (object)[]];
/*entity(e) prop exist in input parameter object*/
if (isset($objt_param->e)) {
$entity=$objt_param->e;
/*entity table exist in schema*/
if (Schema::hasTable($entity)) {
try {
/*get field names */
$arry_field= Schema::getColumnListing($entity);
/*remove id field*/
array_shift($arry_field);
/*prep part1.1: insert into field*/
$strg_sql='insert into '.$entity.'('.implode(",",
$arry_field).')';
/*prep part1.2: field format*/
$strg_sql.=' values ('.implode(",",
array_map(function($v){return '?';},$arry_field)).')';
/*prep part2: field values*/
$objt_reco=$objt_param->reco;
$arry_value=array();
foreach ($arry_field as $field) {
if(isset($objt_reco[$field])){
array_push($arry_value,$objt_reco[$field]);
}else{
array_push($arry_value,null);
}
}
$response->result=DB::insert($strg_sql,$arry_value);
}
catch(\Illuminate\Database\QueryException $ex){
$response->error=$ex->getMessage();
}
catch (ModelNotFoundException $ex) {
$response->error=$ex->getMessage();
}
}/* if table exist */
}/* if prop exist */
return response()->json($response, 200);
}
public function get_insert_record($json=null)
{
$objt_param = (object) json_decode($json, true);
return $this->exec_insert_record($objt_param);
}
public function post_insert_record(Request $request)
{
return $this->exec_insert_record($request);
}
public function exec_update_record($objt_param)
{
$response = (object) ['result' => (object)[],'error' => (object)[]];
/*entity(e) prop exist in input parameter object*/
if (isset($objt_param->e)) {
$entity=$objt_param->e;
/*entity table exist in schema*/
if (Schema::hasTable($entity)) {
try {
/*get field names */
$arry_field= Schema::getColumnListing($entity);
/*remove id field*/
array_shift($arry_field);
/*prep part1: update ... set*/
$strg_sql='update '.$entity.' set ';
/*prep part2: field mask, field value*/
$objt_reco=$objt_param->reco;
$arry_mask=array();
$arry_value=array();
foreach ($arry_field as $field) {
array_push($arry_mask,$field.'=?');
array_push($arry_value,$objt_reco[$field]);
}
$strg_sql.= implode(",",$arry_mask);
/*prep part3: where*/
$strg_sql.=' where id = ?';
array_push($arry_value,$objt_reco['id']);
$response->result=DB::insert($strg_sql,$arry_value);
}
catch(\Illuminate\Database\QueryException $ex){
$response->error=$ex->getMessage();
}
catch (ModelNotFoundException $ex) {
$response->error=$ex->getMessage();
}
}/* if table exist */
}/* if prop exist */
return response()->json($response, 200);
}
public function get_update_record($json=null)
{
$objt_param = (object) json_decode($json, true);
return $this->exec_update_record($objt_param);
}
public function post_update_record(Request $request)
{
return $this->exec_post_record($request);
}
public function exec_delete_record($objt_param)
{
$response = (object) ['result' => (object)[],'error' => (object)[]];
/*entity(e) prop exist in input parameter object*/
if (isset($objt_param->e)) {
$entity=$objt_param->e;
/*entity table exist in schema*/
if (Schema::hasTable($entity)) {
try {
/*prep part1: delete from*/
$strg_sql='delete from '.$entity;
/*prep part2: where*/
$strg_sql.=' where id = '.$objt_param->id;
$response->result=DB::delete($strg_sql);
}
catch(\Illuminate\Database\QueryException $ex){
$response->error=$ex->getMessage();
}
catch (ModelNotFoundException $ex) {
$response->error=$ex->getMessage();
}
}/* if table exist */
}/* if prop exist */
return response()->json($response, 200);
}
public function get_delete_record($json=null)
{
$objt_param = (object) json_decode($json, true);
return $this->exec_delete_record($objt_param);
}
public function post_delete_record(Request $request)
{
return $this->exec_delete_record($request);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$user = User::where('email', $request['email'])->firstOrFail();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function me(Request $request)
{
return $request->user();
}
}
.
.
Surf to https://phpsandbox.io
Create an account e.g. using Google account.
Select Laravel version e.g. Laravel 8
Type a name e.g. lara8api
In config/database.php edit as follows:
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
'default' => env('DB_CONNECTION', 'sqlite'),
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => database_path('database.sqlite'),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
in console window, run command
php artisan migrate
create and run web script to view the created tables.
Route::get('/show_tables',function(){
//$tables = DB::select('SHOW TABLES');
$tables = DB::select("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");
foreach($tables as $table){
$arry = (array) $table;
foreach ($arry as $value) {
echo $value."<br/>";
}
}
});
.
Run console command:
php artisan make:controller AuthController
.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function sign_up(Request $request){
$data = $request->validate([
'name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed'
]);
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
public function login(Request $request)
{
$data = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('email', $data['email'])->first();
if (!$user || !Hash::check($data['password'], $user->password)) {
return response([
'msg' => 'incorrect username or password'
], 401);
}
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
}
.
.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
#single middleware routing
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
#group middleware routing
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/show_users',function(){
$student = DB::select('select * from users');
return response()->json($student, 200);
});
});
#public routing
Route::post('/signup', [AuthController::class, 'sign_up']);
Route::post('/login', [AuthController::class, 'login']);
Route::post('login', [ 'as' => 'login', 'uses' => 'AuthController@do']);
Route::get('/login', function () {
return response([
'error' => 'not logged in'
]);
});
.
Read More.
Surf to https://phpsandbox.io
Create an account e.g. using Google account.
Select Laravel version e.g. Laravel 8
Type a name e.g. lara8api
In config/database.php edit as follows:
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
'default' => env('DB_CONNECTION', 'sqlite'),
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => database_path('database.sqlite'),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
(In route/api.php)
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('/hello', function () {
return( 'hello');
});
Route::get('/init', function () {
Schema::dropIfExists('student');
if (!Schema::hasTable('student')) {
Schema::create('student', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
});
}
$json_data = '{"table":"student","status":"init"}';
$result = json_decode($json_data);
return response()->json($result, 201);
});
Route::match(array('GET', 'POST'),'/getall', function () {
$student = DB::select('select * from student');
return response()->json($student, 200);
});
Route::get('/insert/{name}/{email}',function($name,$email){
$timestamp = time();
DB::insert('insert into student (id, name,email)
values (?, ?,?)',
[$timestamp,$name.'_'.$timestamp,$email.'_'.$timestamp]);
echo "record inserted.<br/>";
});
Route::post('/insert',function(Request $request)
{
$payload = json_decode($request->getContent(), true);
try {
// Get data here, eg. make an external API request or DB query
$response = [
'name' => $payload['name'],
'email' => $payload['email']
];
$timestamp = time();
DB::insert('insert into student (id, name,email)
values (?, ?,?)',
[$timestamp,$response['name'].'_'.$timestamp
,$response['email'].'_'.$timestamp]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
$errorResJson = $e
->getResponse()
->getBody()
->getContents();
$errorRes = json_decode(stripslashes($errorResJson), true);
// Return error
return response()->json(
[
'message' => 'error',
'data' => '$errorRes'
],
$errorRes['response']['code']
);
}
// Return success
return response()->json(
[
'status' => '200',
'data' => '$response',
'message' => 'success'
],
200
);
}
);
Route::post('/update',function(Request $request)
{
$payload = json_decode($request->getContent(), true);
try {
$response = [
'id' => $payload['id'],
'name' => $payload['name'],
'email' => $payload['email']
];
$affected = DB::update(
'update student set name = ?, email=? where id = ?',
[$response['name'],$response['email'],$response['id']]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
$errorResJson = $e
->getResponse()
->getBody()
->getContents();
$errorRes = json_decode(stripslashes($errorResJson), true);
// Return error
return response()->json(
[
'message' => 'error',
'data' => '$errorRes'
],
$errorRes['response']['code']
);
}
// Return success
return response()->json(
[
'status' => '200',
'data' => $affected ,
'message' => 'success'
],
200
);
}
);
Route::post('/delete',function(Request $request)
{
$payload = json_decode($request->getContent(), true);
try {
$response = [
'id' => $payload['id']
];
$deleted = DB::delete('delete from student where id = ?',
[$response['id']]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
$errorResJson = $e
->getResponse()
->getBody()
->getContents();
$errorRes = json_decode(stripslashes($errorResJson), true);
// Return error
return response()->json(
[
'message' => 'error',
'data' => '$errorRes'
],
$errorRes['response']['code']
);
}
// Return success
return response()->json(
[
'status' => '200',
'data' => $deleted ,
'message' => 'success'
],
200
);
}
);
.
Read More
Surf to https://phpsandbox.io
Create an account e.g. using Google account.
Select Laravel version e.g. Laravel 8
Type a name e.g. lara8
In config/database.php edit as follows:
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
'default' => env('DB_CONNECTION', 'sqlite'),
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => database_path('database.sqlite'),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
(In route/web.php)
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/init', function () {
Schema::dropIfExists('student');
if (!Schema::hasTable('student')) {
Schema::create('student', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
});
}
echo "init table.";
});
Route::get('/getall', function () {
$student = DB::select('select * from student');
echo "records:<br/>";
foreach($student as $a_student)
{
echo "record:".$a_student->id."|".$a_student->name."|".$a_student->email."<br/>";
}
});
Route::get('/insert/{name}/{email}',function($name,$email){
$timestamp = time();
DB::insert('insert into student (id, name,email)
values (?, ?,?)',
[$timestamp,$name.'_'.$timestamp,$email.'_'.$timestamp]);
echo "record inserted.<br/>";
});
Route::get('/getone/{id}',function($id){
$result = DB::select('select * from student where id = ?', [$id]);
foreach($result as $a_result)
{
echo "record:<br/>".$a_result->id."|".$a_result->name."|".$a_result->email."<br/>";
}
});
Route::get('/update/{id}/{name}/{email}',function($id,$name,$email){
$affected = DB::update(
'update student set name = ?, email=? where id = ?',
[$name,$email,$id]);
echo "record updated:".$affected;
});
Route::get('/update1/{id}/{name}/{email}',function($id,$name,$email){
$affected = DB::table('student')
->where('id',$id)
->update([
'name'=>$name,
'email'=>$email,
]);
echo "record updated:".$affected;
});
Route::get('/delete/{id}',function($id){
$deleted = DB::delete(
'delete from student where id = ?',
[$id]);
echo "record deleted:".$deleted;
});
Route::get('/delete1/{id}',function($id){
$deleted = DB::table('student')
->where('id', '=',$id)
->delete();
echo "record deleted:".$deleted;
});
Route::get('/show_tables',function(){
//$tables = DB::select('SHOW TABLES');
$tables = DB::select("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");
foreach($tables as $table){
$arry = (array) $table;
foreach ($arry as $value) {
echo $value."<br/>";
}
}
});
https://phpsandbox.io/n/delicate-grass-bdov-ai24b
.
.
Surf to https://phpsandbox.io
Create an account e.g. using Google account.
Select Laravel version e.g. Laravel 8
Type a name e.g. lara8
Edit web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('start');
});
Add other files (html,jss,js) in public folder.
Link to the files using relative path e.g.
<script type="text/javascript" src="./js/app_nav.js"></script>
<script src="./js/app_quiz.js"></script>
.
Read More