Friday, November 2, 2012

XAMPP +PHPMYADMIN

XAMPP +PHPMYADMIN

download XAMPP

Step : # 1
Go the offcial website and click the given blow dowload links
https://www.apachefriends.org/index.html


Step : # 2

Step : # 3

. xampp is a free open sourse cross-platform web server solutions
. xampp is the perfect tools to setup a web server locally


Step : # 4
Run 
. Run as  administrator
. yes
. yes
. un-select Lean about Bitnami for XAMPP
. un-select do you want to

Step : # 5
Go to C drive
like C:\xampp

Step : # 6

download phpMyAdmin

Go the offcial website and click the given blow dowload links
https://www.phpmyadmin.net/



. Extract it
. cut phpMyAdmin and paste inside the C:\xampp\htdocs


. Back to or Go to C:\xampp
. once click it will run automatically





. Open a .new Tab
. localhost/phpmyadmin
http://localhost/phpmyadmin/
or
localhost/phpmyadmin/

Step : # 7

How to create Database and table
New --> Create database --> utf8_general_ci


. Click the database name of the left panel
Then enter table name and  column
like
my table | 4

Step : # 8
. Click the database name then table name of the left panel
. Entry start now
like name - id
 type - INT
 length - 4
 Null Index - PRIMARY
 check box  - thick
storage -> MRG MYISAM

Example like as below

Good output like as below
Database -> Table ->Structure



Step : # 9

What is MySQL?

MySQL is an open-source relational database management system that works on many
platforms, It Provides multi-user access to support many storage engine and is
backend by Oracle So, you can buy a commercial license version from Oracle to get
premium support services.

Advantage of using MySQL with Node.js

1. scalability& Flexibility
2. Low Total Cost of Ownership
3. Secure Data Protection.
4. Ease of Management
5. High performance
6. High Availability
7. Robust Transaction Support
8. Comprehensive Application Development


Workbench
1. XAMPP+ phpMyAdmin

..................................................................................................................................................................................................................................
[Setup Coding ]

const express = require('express')
const mysql = require('mysql')
const app = express()

app.use(express.json())

const mysqlConnection = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'',
    database:'myEdu',
    multipleStatements:true
})
mysqlConnection.connect((error)=>{
    if(!error){
        console.log('connected successful')
    }else{
        console.log('Connection Failed')
    }
})

const port = process.env.PORT || 5000
app.listen(port, () => {
    console.log(`Server is running at ${port}`)
})


//Note: - First create Database then Entry filed the Database  

router.get('/hello', (req, res) => {
    mysqlConnection.query("SELECT * from hello", (error, rows, fields) => {
        if (!error) {
            res.send(rows)
        } else {
            console.log(error)
        }

    })

})
...........................
app.set('views', path.join(__dirname, 'views')
app.set('view', 'hbs')

app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

Step : # 10

const express = require('express')
const mysql = require('mysql')
const bodyParser = require('body-parser')
const router = express.Router()
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))


const mysqlConnection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '',
    database: 'myEdu',
    multipleStatements: true
})


router.post('/hello', (req, res) => {
    const username = req.body.username
    const email = req.body.email
    const sql = `INSERT INTO hello (username, email) VALUES("${username}", "${email}")`
    mysqlConnection.query(sql, (error, results) => {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Updated list' })
    })
})


router.get('/hello', (req, res) => {
    const sql = 'SELECT * FROM hello'
    mysqlConnection.query(sql, (error, results, fields) => {
        if (error) throw error
        return res.send({ results })
    })
})

router.get('/hello/:id', (req, res, ) => {
    const id = req.params.id
    const sql = `SELECT * FROM hello WHERE id= ${id}`
    mysqlConnection.query(sql, (error, row, fields) => {
        if (error) throw error;
        res.send({ error: false, data: row[0], message: 'User list.' })
    })
})

router.put('/hello/:id', (req, res) => {
    const id = req.params.id
    const username = req.body.username
    const email = req.body.email
    const sql = `UPDATE hello SET username="${username}", email="${email}" WHERE id=${id}`
    mysqlConnection.query(sql, (error, results) => {
        if (error) throw error
        res.json({ 'status': "success" })
    })
})



router.delete('/hello/:id', (req, res) => {
    const id = req.params.id
    const sql = `DELETE FROM hello WHERE id=${id}`
    mysqlConnection.query(sql, (error, results) => {
        if(error) {
            res.status(500).send({ error: 'Something failed!' })
          }
          res.json({'status': 'success'})
    })
})

app.use(router)
const port = process.env.PORT || 5000
app.listen(port, () => {
    console.log(`Server running at port ${port}`)

})


Step : # 11 [Some Fundamental  Steps]

1. What is XAMPP?
XAMPP is the most popular PHP development environment.

2. Download
https://www.apachefriends.org/index.html

3. Install locations
c:/xampp

4. Open it XAMPP
localhost/dashboard
click the phpMyAdmin click the Right corner and start Apache and MySQL


5. Open it httpdocs(c:/xampp/httdocs)
create a new folder under httpdocs like codewithhary

6. Some Tips
shift +!
div.container
7. Run the project
http://localhost/codewithhary/

8. Print 
echo "Hello World";
create a variable using $ 

9.variable
$variable1 =34;
$variable =50;

10. print
echo $variable1;
echo $variable2;

11. add
echo $variable1 + $variable2;

12. New lines
echo "<br>";
echo "Data types <br>";
        $var = 30;
        echo var_dump($var);

        $var ="this is First Example";
        echo ($var);

        $var =67.1;
        echo var_dump($var);
13.const
define("pi");

14. Array
<?php

echo "<br>";
$person = array("Johan", "Smith");
echo $person[1];

?>
15. String
$str ="This";
echo $str;
$len = strlen($str);
echo 'lenght is ';
echo $len;

INSERT INTO `trip` (`sno`, `email`, `password`) VALUES ('1', 'sapanindia@gmail.com', '123456');

<?php 

$username="root";
$password="";
$server ="localhost";
$db = "database";
$con = mysqli_connect($server, $username, $password,$db);

if($con){
    echo "Connections Successful ";
}else{
    //echo "No Connection";
    die("No Connections" . mysqli_connect_error());
}
?>
include 'connection.php';
if(isset($_POST['sumit'])){
    $name =$_POST['email'];
    $email =$_POST['password'];
    $sql = "INSERT INTO hello(email, password)VALUES ('$name' , '$email')";
}
if (mysqli_query($con, $sql)) {
    echo "New record created successfully";
  } else {
    echo "Error: " . $sql . "<br>" . mysqli_error($con);
  }
  
  mysqli_close($con);


Most of the frameworks are reliability, consistence and time saver. 
Some of the innovative frameworks are having the rich set of functionalities, so developer no need to write whole code, Developers needs to access the code by using framework and develop a PHP web application. Frameworks don't give the solutions for bad code writers, but it gives reliability while writing code.
................................................................................................................................................................................................................................
Lavel 8

laravel -v
composer global remove laravel/installer
composer global require laravel/installer

View
Component
Blade Template

Route
Middleware
Group Middleware
Route Middle

Form
Form Validations

Model
Migration
Seed

Flash Session
File Upload
Http Method
Http Client

ApI
Multiple Database Connection
Make simple API
Get, Post, Put, Delete

Search
Validation
Api with Resource

Auth
 Sanctum
jetstrem

................................................................................................................................................................................................................................
Step : # 12[ Laravel Installations ]

1. php path 
2. download the composer
3. composer global require laravel/installer

4. laravel 
5. laravel new projectname
6. php artisan serve

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [route]

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

2. Route :: view('sample', 'sample');

3. Route :: get('sample/{id}', function($id){
    echo $id;
    return view ('sample');
});

4. Route :: redirect('youtube', 'sample');

5. Route :: get('/{id}', function($id){
    echo $id;
    return view ('about',['id'=>$id]);
   });
 Route :: view('contact', 'contact');

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class dumpyapi extends Controller
{
    function getData(){
        echo 'Dumppy api';
        "<br>";
        return ['name'=>'Sapan Kumar Das', 'email'=>'email@gmail.com'];
    }
}
Happy Coding :)
................................................................................................................................................................................................................................
Laravel [ Database ]
php artisan make:migration tablename
for Example - 
php artisan make:migration create_table_test

php artisan make:migration create_table_test
php artisan migrate
php artisan migrate:reset
php artisan migrate:rollback  (last table will be delted)

Setup 


Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ UI ]
React
composer require laravel/ui

Install React
php artisan ui react
or
php artisan preset react

Install React with auth
php artisan ui react --auth

npm install && npm run dev
npm run watch -- --watch-poll
..........................................................

Vue
The command below will install laravel/ui in a Laravel project.
composer require laravel/ui

After installing the package, set up Vue by running the artisan command.
php artisan ui vue

Similarly, Livewire is a PHP package that is installed using Composer.
composer require livewire/livewire

Database
1. create a database phpadmin site
2. change the databaseName .env

Happy Coding:)
................................................................................................................................................................................................................................
 Laravel  [Http]
use Illuminate\Support\Facades\Http;

class Demo extends Controller
{
   function demo(){
       return Http::get('https://jsonplaceholder.typicode.com/todos');
   }
}
.............................................
Step -2
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class Demo extends Controller
{
   function demo(){
     $data= Http::get('https://reqres.in/api/users?page=1');
    return view('demo',['collections'=>$data['data']]);
   }
}
..................................................
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>User List</h1>
<table border="3">
<tr>
<td>ID</td>
<td>Email</td>
<td>first_name</td>
<td>last_name</td>
<td>Avatar</td>
</tr>
@foreach ($collections as $user)
<tr>
<td>{{$user['id']}}</td>
<td>{{$user['email']}}</td>
<td>{{$user['first_name']}}</td>
<td>{{$user['last_name']}}</td>
<td><img src ={{$user['avatar']}} alt=''></td>
</tr>
@endforeach
</table>
</body>
</html>

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [Seeds]

How to add dummy data to the database using  command line
php artisan make:seeder MemberSeeder

under Database

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class MemberSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
//members is table name
        DB::table('members')->insert([
            "name"=>Str::random(10),
            "email"=>Str::random(10),
            "password"=>Str::random(10),
        ]);
    }
}
//MemberSeeder is seed name
php artisan db:seed --class=MemberSeeder

Happy Coding:)
................................................................................................................................................................................................................................
 Laravel  [Project]
Basic
  • Install composer
  • Install laravel
Download link as below
  • https://getcomposer.org/ or 
  • command line
Check the composer version
composer

Installing laravel
composer global require laravel/installer

Check it install or not
laravel

Start a Project or create a new project
composer create-project --prefer-dist laravel/laravel projctName
Continue ...
  • Make Controller
  • Make Router
  • Make View
  • Make Layout
  • Add bootStrap and Jquery
Make Controller
php artisan make:controller RestoProject

Make Router
Route::get('/', [RestoProject::class, 'index']);

Make View
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class RestoProject extends Controller
{
    function index(){
        return view('home');
    }
}

Make Layout

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    @extends('layout')
    @section('content')
    <h2> Home Page here </h2>
    @stop 

</body>
</html>
.........................................
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restaurants App</title>
</head>

<body>
    <header>Menu Here!</header>
    @yield('content')
<footer>
@ Copy rights by Restaurants Apps
</footer>
</body>
</html>

Happy Coding:)
................................................................................................................................................................................................................................
 Laravel  [Database]

make a controller with some stuff
php artisan make:controller bookController --resource

make model and create table
php artisan make:model books -m

php artisan migrate

public function index()
    {
        return books::orderBy('created_at', "DESC")->get();
    }


    public function store(Request $request)
    {
        $newItem = new books;
        $newItem->name = $request->book['name'];
        $newItem->email =$request->book['email'];
        $newItem->save();
        return $newItem;
    }

Api

Route::get('book', [bookControllertroller::class, 'index']);
Route::prefix('/book')->group(function(){
    Route::post('/store',[bookController::class, 'store']);

});

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [React + Laravle]

1. Install Laravel Project
composer create-project laravel/laravel --prefer-dist laravel-react-js

2. Get into the Laravel project.
cd laravel-react-js

3. Install laravel/ui
composer require laravel/ui

4. Install React in Laravel
php artisan ui react

5. Install Required Packages
npm install && npm run dev

6. We have to register the React component inside the resources/js/app.js file.
require('./bootstrap');

// Register React components
require('./components/Example');
require('./components/User');

7. Place the given below code inside the views/welcome.blade.php template.

<body>
    <div id="example"></div>
    <script src="{{ asset('js/app.js') }}" defer></script>
    </body>
or
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

 npm run watch

php artisan serve

# for development
npm run dev

# for production
npm run production

8. Install Bootstrap 
Run command to install Bootstrap in Laravel project.
php artisan ui bootstrap

9. Install Bootstrap Auth Scaffolding
php artisan ui bootstrap --auth

npm install
npm run watch

10. Error
In my work environment root, .babelrc file was not there. However, following entry in package.json solved the issue.

"babel": {
"presets": [
  "@babel/preset-env",
  "@babel/preset-react"
],
"plugins": [
  "@babel/plugin-proposal-class-properties"
]}
................................
rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force

Then run the command
npm install cross-env

npm install 
and then you can also run

npm run dev
.......................................................
Route
Route::view('add', 'addMember');
return redirect('api/v1/store')

model
 public $timestamps=false;
 protected $fillable=['name', 'email'];
protected $table =""

form
<form>
@csrf
</form>
or
return $request->input();
...............................................
 Api

<form action="submit" method="POST">
    @csrf
    <input type="text" name="name" id="name"><br><br>
    <input type="text" name="email" id="email"><br><br>
    <button type="submit">Submit </button>
    </form>
...............................

public function store(Request $request)
    {
      $newuser =new UserModel;
      $newuser->name = $request->name;
      $newuser->email= $request->email;
      $newuser->save();
      return redirect('form');
    }
or
    public function store(Request $request)
    {
        $newuser =new UserModel;
        $newuser->name = $request->name;
        $newuser->email= $request->email;
       $newuser->save();
      return redirect('api/v1/form');
    }
.....................................................
React POST Method

import React, { useState } from 'react';
import { Button } from 'react-bootstrap';
import { useHistory } from 'react-router-dom'

function Register() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const history = useHistory();

    const onHandleSubmit = async (e) => {
        e.preventDefault();
        let result = await fetch('http://localhost:8000/api/register', {
            method: 'POST',
            mode: 'cors',
            body: JSON.stringify({ name, email, password }),
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json"
            }
        })
        result = await result.json();
        console.log("results", result);
        localStorage.setItem("user-info", JSON.stringify(result));
        history.push('add')
    }

    return (
        <div className="col-sm-6 offset-sm-3">
            <h3> Register Page</h3>
            <input type="text" className="form-control" value={ name } onChange={ (e) => setName(e.target.value) } placeholder="Enter Name" /><br />

            <input type="text" className="form-control" value={ email } onChange={ (e) => setEmail(e.target.value) } placeholder="Enter Email" /><br />

            <input type="text" className="form-control" value={ password } onChange={ (e) => setPassword(e.target.value) } placeholder="Enter Password" /> <br />

            <Button onClick={ onHandleSubmit }> Sign Up</Button>
        </div>
    )
}
export default Register;

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [Flutter]

import 'dart:convert';
import 'dart:async';
import 'package:firebaseProject/models/user.dart';
import 'package:http/http.dart' as http;

class ApiService {
  Future<User> getData() async {
    print('Hello');
    final String url = 'http://10.0.2.2:8000/api/v1/v';
    http.Response response = await http.get(url, headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json'
    });
    if (response.statusCode == 200) {
      User user = userFromJson(response.body);
      print(user.name);

      return user;
    } else {
      throw new Exception('Error');
    }
  }
}
..............................
Get
public function index()
    {
        return FlutterModel::all();
    }
..................................

API
import 'package:hello/models/user.dart';
import 'package:http/http.dart' as http;

class UserService {
  Future<List<User>> getUser() async {
    final String url = 'http://10.0.2.2:8000/api/v1/user/';
    http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      List<User> user = userFromJson(response.body);
      return user;
    } else {
      throw new Exception();
    }
  }
}
..........................
itemCount: snapshot.data?.length ?? 0,
get length => null;

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ Route + React  ]

Route

Route::view('form',"userView");   //userView.blade.php
Route::post('submit',[UserView::class, 'store']);
...............................................
Api

Route::prefix('v1')->group(function(){
Route::view('form',"userView");
Route::post('submit',[UserView::class, 'store']);

});
...............................................
React

Route::view('/{any}', 'app')->where('any', '.*');
or
//Route::view('/{path?}', 'app');

app.blade.php

<!DOCTYPE html>
    <html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- CSRF Token -->
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Tasksman</title>
        <!-- Styles -->
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    </head>
    <body>
        <div id="example"></div>
        <script src="{{ asset('js/app.js') }}"></script>
    </body>
    </html>

...............................................
@extends("master")
@yield('content')

@section("content")
@endsection

{{View::make('footer')}}
..............................................
API with Resource

php artisan make:controller SapanController --resource

 return ["results"=>"Data List"];

Route::apiResource('/member',SapanController::class);
http://127.0.0.1:8000/api/member
...............................................
Create Model and resource single command

php artisan make:model Device -mcr
...............................................

...............................................

...............................................
................................................................................................................................................................................................................................
 Laravel  [Session ]

$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
.............................
function register(Request $req){
return $req->input();
}
............................
Model 
$user = new User;
$user->name=$req->input('name');
$user->email=$req->input('email');
$user->password=Hash($req->input('email'));
$user->save();
return $user;
.............................
profile.blade.php
  <h2> Profile</h2>
        <h2>{{ session('user')}}</h2>

...............................
    <h2>Login Form</h2>
    <form action="/users" method="POST">
    @csrf
    <input type="text" name="user"><br><br>
    <input type="text" name="password"><br><br>
    <button type="submit">Submit</button>
    </form>
................................
 public function store(Request $request)
    {
       // return $request->input();
       $data = $request->input('user');
       $request->session()->put('user session',$data );
      // echo session('password');
       return redirect('profile');
    }
..................................................
Route::get('/{id}',[HomeController::class,'index']);
Route::get('/contact',[HomeController::class,'contact']);
Route::post('/contact',[HomeController::class,'contactPost']);

public function index($id)
{
return view('welcome',['id'=>$id]);
}
public function contact()
{
return view('contact');
}
public function contactPost(Request $request)
{
//return view('contact');
$name=>$request->input('name');
$email=>$request->input('email');
$echo $email
}

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [Flash Message]

return redirect('profile')->with('success', 'Successfull Submitted Here')

profile.blade.php
@if(session('success'))
<div> {{session('success')}}</div>
@endif
................................................................................................................................................................................................................................
 Laravel  [ Middleware]

return ["result"=>"data has been saved"]

What is middleware

global middleware available for all pages
group middleware 10 page
router middleware single route at a time

............
Route::view('home', 'home');
Route::view('/login', 'login');
Route::view('/no', 'noaccess');
Route::view('/login', 'login');
Route::view('/no', 'noaccess')->middleware('page');
Route::group(['middleware' => ['page']], function () {
Route::view('home', 'home');
Route::get('/', function () {
    return view('welcome');
});
});
................................................................................................................................................................................................................................
 Laravel  [ Seeder ]

Migrations
php artisan make:migration create_ecommerce_table
php artisan migrate

Seeder
php artisan make:seeder Emcoseeder
php artisan db:seed --class Emcoseeder

example

  DB::table('ecommerce')->insert([
            'name'=>'Sapan Kumar Das',
            'email'=>'sapan@gmail.com',
            'password'=>Hash::make('123456'),

        ]);


Error
Schema::defaultStringLength(191);

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ jetstream ]

composer install
brew install composer //for MAC
        
php artisan make:controller StudentController --resource--model=Student

laravel --version
upgrade
composer global update
install jetstream
laravel new l8 --jet --dev
>0
>yes

ceate a new Project => composer create-project --prefer-dist laravel/laravel laravel8

php artisan make:model Post -m  
-m -> migration

php artisan make:model Post -m

create factory
php artisan make:factory PostFactory

php artisan db:seed


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

@extends('master')

............................................................................
Coding

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class Users extends Controller
{
    function fetchData(){
        echo 'Well come laravel 8';
        return view('Userview');
    }

   public function getuser(){
       $users = DB::select("SELECT * FROM user");
      // $users = DB::select("SELECT * FROM user WHERE id=2");
    // $users = DB::select("SELECT  * FROM user WHERE id=?", [1]);
   //name binding parametrs
       $users = DB::select("SELECT * FROM user WHERE id=:id", ["id"=>1]);

      // echo "<pre>";
      // print_r($users);
      foreach($users as $user){
          echo $user->name."<br>";
      }
   }
}

Insert
public function insertdata(){
    $userss = DB::insert("INSERT INTO user(name, email, phone) VALUES(?, ?,?)", ["Michel", "michel@gmail.com", "44444444"]);
    print_r($userss);
    }

Update
public function updatadate(){
    $update = DB::update("UPDATE user SET email=? WHERE id=?",["sa@gmail.com","1"]);
    print_r($update);
}

Delete
public function deleteuser(){
    $delte =DB::delete("DELETE FROM user WHERE id=:id",['id'=>2]);
    print_r($delte);
}
......................................................
routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Users;

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

Route::get('users',[Users::class,"getuser"]);

controller/
class dumController extends Controller
{
    function getData(){
        return ['Username'=>'Sapan'];
    }
}

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ Sanctum]




Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ Passport ]

Installing Laravel
Open your command line terminal and run the command
composer create-project --prefer-dist laravel/laravel LaravelAPI

Install passport package
Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use.
Within your new project directory, run the command

Step : #1
Installations
composer require laravel/passport
................................
Step : #2
Laravel\Passport\HasApiTokens trait to your App\Models\User model
app/Models/User.php

use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
................................
Step : #3
Next, you should call the Passport::routes method within the boot method of your App\Providers\AuthServiceProvider

use Laravel\Passport\Passport;
public function boot()
    {
        $this->registerPolicies();
            Passport::routes();  
    }
................................
Step : #4
Next, we’ll edit the file app/Providers/AppServiceProvider.php and import the Illuminate\Support\Facades\Schema class by adding.

use Illuminate\Support\Facades\Schema
Schema::defaultStringLength(191);
................................
Step : #5
Finally, in your application's config/auth.php configuration file, you should set the driver option of the api authentication guard to passport.
config/auth.php

        'driver' => 'passport',
................................
Step : #6
php artisan migrate
php artisan passport:install
................................
CORS
https://github.com/fruitcake/laravel-cors
Install 
composer remove barryvdh/laravel-cors fruitcake/laravel-cors
composer require fruitcake/laravel-cors

Set the Middleware
protected $middleware = [
  \Fruitcake\Cors\HandleCors::class,
    // ..
];


config/cors.php



or
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    // 'allowed_origins' => ['http://127.0.0.1:8080/', 'http://localhost:8080/'], <-- doesn't work, still gets CORS error
    'allowed_origins' => ['*'],  // <-- it works but it should not be like that
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['content-type', 'accept', 'x-custom-header', 'Access-Control-Allow-Origin'],
    // 'allowed_headers' => ['*'],
    'exposed_headers' => ['x-custom-response-header'],
    'max_age' => 0,
    'supports_credentials' => false,
];


Run the terminal
php artisan vendor:publish --tag="cors"
..................................

Code Here

Create a controller
 php artisan make:controller Auth\LoginController 

LoginController
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'email'=>'required|email',
            'password'=>'required'
        ]);
        if($validator->fails()){
            return response()->json([
                'error'=>$validator->errors()
            ]);
        }

        $credentials = [
            'email' => $request->email,
            'password' => $request->password
        ];

        if (auth()->attempt($credentials)) {
            
            /** @var \App\Models\User */
            $user = Auth::user();
            $success['token'] = $user->createToken('AppName')->accessToken;
            return response()->json([
                'success' => $success, 
                'message' => 'Login Successful!',
                "Name"=>$user['name']], 200);
        } else {
            return response()->json([
                'message' => 'Unauthorized',
            ], 401);
        }
    }
}

......................................................
RegisterController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    public function register(Request $request){

        $newuser =$request->all();
        $validator = Validator::make($request->all(),[
            'name'=>"required",
            'email'=>'required|email|unique:users',
            'password'=>'required'
        ]);
        if($validator->fails()){
            return response()->json([
                'error'=>$validator->errors()
            ]);
        }
        
        $newuser['password']=Hash::make($newuser['password']);
        $user = User::create($newuser);
        $success['token']=$user->createToken('AppName')->accessToken;
        return response()->json([
            'success'=>$success,
            'message' => 'Successfull created user!'

        ],200);
    }
  
}
....................................
api.php

Route::post('register',[RegisterController::class,'register']);
Route::post('login',[LoginController::class,'login']);

............................................................................................................................................................................................................................

After successful installation, create a database and edit the database config section in .env file created.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_DB_NAME
DB_USERNAME=root
DB_PASSWORD=


Database/migrations

public function up()
{
    Schema::create('users', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('fname');
       $table->string('lname');
       $table->string('phone');
       $table->string('email')->unique();
       $table->timestamp('email_verified_at')->nullable();
       $table->string('password');
       $table->rememberToken();
       $table->timestamps();
   });
}

Now, run the migration command:
............................................
php artisan migrate

Error


Route::group(['prefix' => 'v1'], function () {
    Route::get('post',[dumController::class, 'getData']);
});

class DumyApi extends Controller
{
    function fetchData(){
        return ["name"=>"Sapan", 'email'=>'sapan@gmail.com'];

    }
}

Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ Deploy A Laravel App to Heroku ]

Step :#1
Inside the Laravel Root folder, make a file called Procfile

Write the following line inside the Procfile.

web: vendor/bin/heroku-php-apache2 public/

For Example


Step :#2 
https://dashboard.heroku.com/apps






Heroku

/storage/*.key
web:vendor/bin/heroku-php-apache2 public/


git remote -v
heroku  https://git.heroku.com/thawing-inlet-61413.git (fetch)
heroku  https://git.heroku.com/thawing-inlet-61413.git (push)

heroku git:remote -a laraveleshop
heroku git:remote -a thawing-inlet-61413

git push heroku master

heroku pg:credentials:url

heroku config:add DB_CONNECTION=pgsql
heroku config:add DB_HOST=ec2-3-215-76-208.compute-1.amazona
heroku config:add DB_PORT=5432
heroku config:add DB_DATABASE=d2hi9hajdb9uo8
heroku config:add DB_USERNAME=agewtyfbnxzfah
heroku config:add DB_PASSWORD=486a9db32

heroku config:add APP_KEY=
heroku config:add APP_DEBUG=false
heroku config:add APP_ENV=production
heroku config:add APP_NAME=Laravel

heroku run php artisan migrate 


composer require laravel/passport
php artisan migrate
php artisan passport:install
php artisan passport:keys
cors

            
X-Requested-With: XMLHttpRequest
Content-Type: application/json

How get API_KEY
php artisan key:generate --show

Using Command 
heroku config:set APP_DEBUG=false


Where we're get all above that just a look at the below as images




Step : #3 [ Database Setting ]

Adding Postgres
From the application dashboard on Heroku, go to the ‘resources’ tab and search for postgres. Provision it and use the free option and install it




/storage/*.key
Heroku command
heroku update
heroku login -i
heroku create laraveleshop
git remote -v
git push heroku master


Seeting https [secure connections ]

public\.htaccess

RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

C:\xampp\htdocs\restapi\app\Http\Middleware\TrustProxies.php

  //  protected $proxies;
    protected $proxies = '*';




Vendor
require('vendor/autoload.php');
composer update



Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ Project ]




Happy Coding :)
................................................................................................................................................................................................................................
 Laravel  [ Project ]










No comments:

Post a Comment