PHP & Web Development Blogs

Search Results For: notification
Showing 1 to 4 of 4 blog articles.
4203 views · 1 years ago

![Why Cloudways is the Perfect Managed Hosting for PHP Applications](https://images.ctfassets.net/vzl5fkwyme3u/3VLCUBagZPfSLyxyt1AvvP/89e3b904a450454545eb885e2e0e76b4/cloudways.jpg?w=1000)

#### The following is a sponsored blogpost by [Cloudways](https://www.cloudways.com/en/?id=431739)

Developing an application is not the sole thing you should bank on. You must strive to find the best hosting solution to deploy that application also. The application’s speed is dependent on the hosting provider, that is why I always advise you to go for the best hosting solution to get the ultimate app performance.

Now a days, it is a big challenge to choose any web hosting, as each hosting has its own pros and cons which you must know, before considering it finally for the deployment. I don’t recommend shared hosting for PHP/Laravel based applications, because you always get lot of server hassles like downtime, hacking, 500 errors, lousy support and other problems that are part and parcel of shared hosting.

For PHP applications, you must focus on more technical aspects like caching, configs, databases, etc. because these are essential performance points for any vanilla or framework-based PHP application. Additionally, if the app focuses on user engagement (for instance, ecommerce store), the hosting solution should be robust enough to handle spikes in traffic.

Here, I would like to introduce Cloudways [PHP server hosting](https://www.cloudways.com/en/php-cloud-hosting.php?id=431739) to you which provides easy, developer and designer friendly managed hosting platform. With Cloudways, you don't need to focus on PHP hosting, but must focus on building your application. You can easily launch cloud servers on five providers including DigitalOcean, Linode, Vultr, AWS and GCE.

### Cloudways ThunderStack

Being a developer, you must be familiar with the concept of stack - an arrangement of technologies that form the underlying hosting solution.

To provide a blazing fast speed and a glitch-free performance, Cloudways has built a PHP stack, known as ThunderStack. This stack consists of technologies that offer maximum uptime and page load speed to all PHP applications. Check out the following visual representation of ThunderStack and the constituent technologies:

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/5v08m0nwsFPv7niXjmRX0M/ca3aba8d814578baf676bd58c3933dc8/cloudways_image1.png?w=1000)

As you can see, ThunderStack comprises of a mix of static and dynamic caches with two web servers, Nginx and Apache. This combination ensures the ultimate experience for the users and visitors of your application.

### Frameworks and CMS

The strength and popularity of PHP lies in the variety of frameworks and CMS it offers to the developers. Realizing this diversity, Cloudways offers a hassle-free installation of major PHP frameworks including Symfony, Laravel, CakePHP, Zend, and Codeigniter. Similarly, popular CMS such as WordPress, Bolt, Craft, October, Couch, and Coaster CMS - you can install these with the 1-click option. The best part is that if you have a framework or CMS that is not on the list, you can easily install it through Composer.

### 1-Click PHP Server & Application Installation

Setting up a stack on an unmanaged VPS could take an entire day!

When you opt for Cloudways managed cloud hosting, the entire process of setting up the server, installation of core PHP files and then the setup of the required framework is over in a matter of minutes.

Just [sign up at Cloudways](https://www.cloudways.com/en/?id=431739), choose your desired cloud provider, and select the PHP stack application.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/2Dp11Kg9FOkHkFbjUub7Tj/f0c4c125a8c683c51a548fdd287c8330/cloudways_image2.png?w=1000)

As you can see, your LAMP stack is ready for business in minutes.

Many PHP applications fail because essential services are either turned off or not set up properly. Cloudways offers a centralized location where you can view and set the status of all essential services such as:

* Apache

* Elasticsearch

* Memcached

* MySQL

* PHP-FPM

* Nginx

* New Relic

* Redis

* Varnish

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/1zvZI0b7zuPbBacp4ALAax/a5150babfbe2972c96beca3ac71395f2/cloudways_image3.png?w=1000)

Similarly, you can manage SMTP add-ons without any fuss.

### Staging Environment

With Cloudways, you can test your web applications for possible bugs and errors before taking it live.

Using the staging feature, developers can first deploy their web sites on test domains where they can analyze the applications performance and potential problems. This helps site administrators to fix those issues timely and view the application performance in real-time.

A default sub domain comes pre-installed with the newly launched application, making it easy for the administrators to test the applications on those testing subdomains. Overall, it's a great feature which helps developers know about the possible errors that may arise during the live deployment.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/5gTrIsw9KjhocjtZMWVePB/a8274899ee55d7068329c551af362fdf/cloudways_image4.png?w=1000)

### Pre-Installed Composer & Git

PHP development requires working with external libraries and packages. Suppose you are working with Laravel and you need to install an external package. Since Composer has become the standard way of installing packages, it comes preinstalled on the Cloudways platform. Just launch the application and start using Composer in your project.

Similarly, if you are familiar with Git and maintain your project on GitHub or BitBucket, you don’t need to worry about Git installation. Git also comes pre-configured on Cloudways. You can start running commands right after application launch.

### Cloudways MySQL Manager

When you work with databases in PHP, you need a database manager. On the Cloudways platform, you will get a custom-built MySQL manager, in which you can perform all the tasks of a typical DB manager.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/415qced8tKK8FWEsWGPhAm/ec1947d0b21ac8cd572613d0a1fa88dc/cloudways_image5.png?w=1000)

However, if you wish to install and use another database manager like PHPMyAdmin, you can install it by following this simple guide on installing [PHPMyadmin](https://www.cloudways.com/blog/installation-phpmyadmin/?id=431739).

### Server & Application Level SSH

If you use Linux, you typically use SSH for accessing the server(s) and individual applications. A third-party developer requires application and server level access as per the requirements of the client. Cloudways offers SSH access to fit the requirements of the client and users.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/1IpSR4TrckMFJjYQ1m5upz/030f71f106b7db97ce16de10aba2c17b/cloudways_image6.png?w=1000)

### PHP-FPM, Varnish & Cron Settings

Cloudways provides custom UI panel to set and maintain PHP-FPM and Varnish settings. Although the default configuration is already in place, you can easily change all the settings to suit your own, particular development related requirements. In Varnish settings, you can define URL that you want to exclude from caching. You can also set permissions in this panel.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/2W8XQvGa3CZAPBwUY4sqca/8a6b041c6dc850cc2715bb19eb17a464/cloudways_image7.png?w=1000)

Cron job is a very commonly used component of PHP application development process. On Cloudways platform, you can easily set up Cron jobs in just a few clicks. Just declare the PHP script URL and the time when the script will run.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/32fN2IkC1X3HEC2Ly685nz/6fb9607bab9beaa81bff1b7fe4061edf/cloudways_image8.png?w=1000)

### Cloudways API & Personal Assistant Bot

Cloudways provides an internal API that offers all important aspects of the server and application management. Through Cloudways API, you can easily develop, integrate, automate, and manage your servers and web apps on Cloudways Platform using the RESTful API. Check out some of the [use cases developed](https://www.cloudways.com/blog/category/use-cases/api/?id=431739) using Cloudways API. You just need your API key and email for authentication of the HTTP calls on API Playground and custom applications.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/5Uxx5XySaV2um2AnJjvbcg/0a4e997995d6644aa90c850a41db2720/cloudways_image9.png?w=1000)

Cloudways employs a smart assistant named CloudwaysBot to notify all users about server and application level issues. CloudwaysBot sends the notifications on pre-approved channels including email, Slack and popular task management tools such as Asana and Trello.

### Run Your APIs on PHP Stack

Do you have your own API which you want to run on the PHP stack? No problem, because you can do that, too with Cloudways! You can also use REST API like [Slim](https://www.cloudways.com/blog/simple-rest-api-with-slim-micro-framework/?id=431739&utm_source=phpjabber&utm_medium=referral), [Silex](https://www.cloudways.com/blog/create-rest-api-silex/?utm_source=phpjabber&utm_medium=referral&id=431739), [Lumen](https://www.cloudways.com/blog/creating-rest-api-with-lumen/?utm_source=phpjabber&utm_medium=referral&id=431739), and others. You can use APIs to speed up performance and require fast servers with lots of resources. So, if you think that your API response time is getting slower due to the large number of requests, you can easily scale your server(s) with a click to address the situation.

### Team Collaboration

When you work on a large number of applications with multiple developers, you need to assign them on any specific application. Cloudways provides an awesome feature of team collaboration through which you can assign developers to specific application and give access to them. You can use this tool to assign one developer to multiple applications. Through team feature, you can connect the team together and work on single platform. Access can be of different type; i.e. billing, support and console. You can either give the full access or a limited one by selecting the features in Team tab.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/3Yn7GSeHrLvSbPf42RTR2n/269328c371e80f3ac87984cf46b6e9ac/cloudways_image10.png?w=1000)

### Final Words

Managed cloud hosting ensures that you are not bothered by any hosting or server related issues. For practical purposes, this means that developers can concentrate on writing awesome code without worrying about underlying infrastructure and hosting related issues. Do [sign up](https://www.cloudways.com/en/?id=431739) and check out Cloudways for the best and the most cost-effective cloud hosting solution for your next PHP project!

3919 views · 1 years ago

![Implement Web Push Notification in PHP using W3C provided Notification API](https://images.ctfassets.net/vzl5fkwyme3u/ERmW7y6S781gcWIiFjTRn/de1c1aeb3c79093210828760fc373ab2/AdobeStock_152541972.png?w=1000)

Hi Guys,

I am sharing you the simple steps by which you can broadcast the web push notifications to your subscriber. In this tutorial we are making a subscriber form and saving information using Ajax and PHP and then through a server side code returning response to current logged in user and showing notification to that user.

**Following are the steps to build this system**

#### 1. Create a database, I am creating db with name 'web_notifications'

Creating subscribers and notifications tables using following sql statements

```

CREATE TABLE IF NOT EXISTS `subscribers` (

`id` int(11) NOT NULL,

`name` varchar(255) NOT NULL,

`email` varchar(255) NOT NULL,

`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `subscribers`

ADD PRIMARY KEY (`id`);

ALTER TABLE `subscribers`

MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

CREATE TABLE IF NOT EXISTS `notifications` (

`id` int(11) NOT NULL,

`to_user` int(11) NOT NULL,

`title` varchar(255) NOT NULL,

`body` varchar(255) NOT NULL,

`url` varchar(255) NOT NULL,

`is_sent` int(11) NOT NULL DEFAULT '0',

`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `notifications`

ADD PRIMARY KEY (`id`);

ALTER TABLE `notifications`

MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

```

#### 2. Now create a db_connect.php file with following code

```

<?php

session_start();

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "web_notifications";

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

?>

```

#### 3. Create a cookies.js file to read and write browser cookies

```

function WriteCookie(key,content) {

var now = new Date();

now.setMonth( now.getMonth() + 1 );

document.cookie = key+"=" + escape(content) + ";";

document.cookie = "expires=" + now.toUTCString() + ";"

}

function ReadCookie(key) {

var allcookies = document.cookie;

cookiearray = allcookies.split(';');

var CookieData=Array();

for(var i=0; i<cookiearray.length; i++) {

k = cookiearray[i].split('=')[0];

v = cookiearray[i].split('=')[1];

CookieData[k]=v;

}

return CookieData[key];

}

```

#### 4. Create a ajax file to read and mark is_sent if any notification foun to be sent in database for that user. create file with name 'fetch_notifications.php' with following content

```

<?php require 'db_connect.php';

$sql = "SELECT id,title,body,url FROM notifications where to_user='"[email protected]$_GET['user_id']."' and is_sent='0' ";

$result = $conn->query($sql);

$data=array();

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

$data[]=$row;

/ /update this record as is_sent

$upd = "update notifications set is_sent='1' where id='".$row['id']."' ";

$conn->query($upd);

}

}

if(count($data)>0)

{

$response=array("status"=>1,"notification"=>$data);

}

else

{

$response=array("status"=>0,"error"=>"No new notification!");

}

echo json_encode($response);

$conn->close();

?>

```

#### 5. Now code index.php to show subscriber form and on submit insert record into the subscriber table

```

<?php require 'db_connect.php'; ?>

<!DOCTYPE html>

<html>

<head>

<title>Web Push Notification Demo</title>

<script src="./cookies.js" type="text/javascript"></script>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<?php

if(isset($_POST['subscribe_form']))

{

$_SESSION['is_login']=0;

$username=$conn->real_escape_string($_POST['username']);

$useremail=$conn->real_escape_string($_POST['useremail']);

$sql = "INSERT INTO subscribers set name='".$username."',email='".$useremail."' ";

if ($conn->query($sql) === TRUE) {

$_SESSION['is_login']=1;

$_SESSION['Uid']= $conn->insert_id;

$_SESSION['Uname']= $username;

?>

<script type="text/javascript">

WriteCookie("Uid","<?php echo $_SESSION['Uid']; ?>");

</script>

<?php

$msg="<p style='color:green'>You have subscribe for push notification succesfully :)</p>";

} else {

$msg="<p style='color:red'>Error in subscribing for notifications</p>";

}

}

?>

<div class="container">

<?php

if(isset($msg) && $msg!='')

{

?>

<br>

<div class="alert alert-info">

<?php echo $msg; ?>

</div>

<?php

}

if(isset($_SESSION['is_login']) && $_SESSION['is_login']==1)

{

?>

<h2>Welcome <?php echo $_SESSION['Uname']; ?></h2>

<script type="text/javascript">

setInterval(function(){

check_notification();

}, 10000);

function check_notification()

{

var Uid=ReadCookie("Uid");

if(Uid!==undefined)

{

$.ajax({url: "fetch_notifications.php?user_id="+Uid, success: function(result){

var response=JSON.parse(result);

if(response.status==1)

{

response=response.notifications;

for (var i = response.length - 1; i >= 0; i--) {

var url = response[i]['url'];

var noti = new Notification(response[i]['title'], {

icon: 'logo.png',/ /this should be your logo in root folder

body: response[i]['body'],

});

noti.onclick = function () {

window.open(url);

noti.close();

};

};

}

else{

console.log(response.error);

}

}

});

}

}

</script>

<?php

}

else

{

?>

<h2 class="text-center">Subscribe for Notifications</h2>

<div class="row justify-content-center">

<div class="col-12 col-md-8 col-lg-6 pb-5">

<div class="card border-primary rounded-0">

<div class="card-header p-0">

<div class="bg-info text-white text-center py-2">

<h3><i class="fa fa-envelope"></i> Information</h3>

<p class="m-0">provide your information</p>

</div>

</div>

<div class="card-body p-3">

<form method="post">

<!--Body-->

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-user text-info"></i></div>

</div>

<input type="text" class="form-control" id="username" name="username" placeholder="Input Your Name Here" required>

</div>

</div>

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-envelope text-info"></i></div>

</div>

<input type="text" class="form-control" id="useremail" name="useremail" pattern="[^@\s][email protected][^@\s]+\.[^@\s]+" title="Invalid email address" placeholder="[email protected]" required>

</div>

</div>

<div class="text-center">

<input type="submit" value="Subscribe" name="subscribe_form" class="btn btn-info btn-block rounded-0 py-2">

</div>

</form>

</div>

</div>

</div>

</div>

<?php }?>

</div>

</head>

<body>

</body>

</html>

<?php

$conn->close();

?>

```

The frontend of your subscription page (index.php) should look like this:

![Subscribing Form to User](https://www.w3school.info/blogimages/front_web_push_page.png)

Now we are ready to receive notification in frontend, but we still need to create an admin page from where we can send notification to subscriber(s).

#### 6. Create a table for admin user

```

CREATE TABLE IF NOT EXISTS `admin` (

`id` int(11) NOT NULL,

`username` varchar(255) NOT NULL,

`password` varchar(255) NOT NULL,

`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `admin`

ADD PRIMARY KEY (`id`);

ALTER TABLE `admin`

MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

INSERT INTO `web_notifications`.`admin` (`id`, `username`, `password`, `createdAt`) VALUES (NULL, 'admin', MD5('123456'), CURRENT_TIMESTAMP);

```

Following is the code for admin.php to add the notifications to subscriber(s) account also i have inserted following login credentials for admin in admin table:

username:admin

password:123456

#### 7. Now put following code in admin.php

```

<?php require 'db_connect.php'; ?>

<!DOCTYPE html>

<html>

<head>

<title>ADMIN PAGE</title>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<?php

if(isset($_POST['login']))

{

$_SESSION['admin_login']=0;

$username=$conn->real_escape_string($_POST['username']);

$password=$conn->real_escape_string($_POST['password']);

$sql = "SELECT * FROM admin where username='".$username."' and password='".md5($password)."' ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

$_SESSION['admin_login']=1;

$msg="<p style='color:green'>Admin Logged-in Successfully :)</p>";

}

else {

$msg="<p style='color:red'>INVALID CREDENTIALS FOR ADMIN</p>";

}

}

if(isset($_POST['add_notification']))

{

$title=$conn->real_escape_string($_POST['title']);

$body=$conn->real_escape_string($_POST['body']);

$url=$conn->real_escape_string($_POST['url']);

$users=$_POST['users'];

foreach ($users as $user_id) {

$ins = "insert into notifications set to_user='".$user_id."' , title='".$title."', url='".$url."', body='".$body."' ";

$conn->query($ins);

}

$msg="<p style='color:green'>Notification(s) added to subscribers account.</p>";

}

?>

<div class="container">

<?php

if(isset($msg) && $msg!='')

{

?>

<br>

<div class="alert alert-info">

<?php echo $msg; ?>

</div>

<?php

}

if(isset($_SESSION['admin_login']) && $_SESSION['admin_login']==1)

{

?>

<h2>Welcome Admin, Send notification to Subscriber(s)</h2>

<form method="post">

<div class="form-group">

<label for="sel1">Select Subscriber(s):</label>

<select multiple="multiple" required="required" class="form-control" id="users" name="users[]">

<?php

$sql = "SELECT id,name FROM subscribers";

$result = $conn->query($sql);

$data=array();

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

echo "<option value='".$row['id']."'>".$row['name']."</option>";

}

}

?>

</select>

</div>

<div class="form-group">

<label for="email">Title</label>

<input type="text" required class="form-control" placeholder="notification title here" name="title" id="title">

</div>

<div class="form-group">

<label for="email">Message</label>

<textarea required class="form-control" placeholder="notification message here" name="body" id="body"></textarea>

</div>

<div class="form-group">

<label for="email">Url</label>

<input type="url" required class="form-control" placeholder="notification landing/click url here" name="url" id="url">

</div>

<input type="submit" class="btn btn-primary btn-block" name="add_notification" value="Submit" />

</form>

<?php

}

else

{

?>

<h2 class="text-center">ADMINISTRATOR</h2>

<div class="row justify-content-center">

<div class="col-12 col-md-8 col-lg-6 pb-5">

<div class="card border-primary rounded-0">

<div class="card-header p-0">

<div class="bg-info text-white text-center py-2">

<h3><i class="fa fa-envelope"></i> LOGIN</h3>

<p class="m-0">provide admin login credentials</p>

</div>

</div>

<div class="card-body p-3">

<form method="post">

<!--Body-->

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-user text-info"></i></div>

</div>

<input type="text" class="form-control" id="username" name="username" placeholder="Input username here" required>

</div>

</div>

<div class="form-group">

<div class="input-group mb-2">

<div class="input-group-prepend">

<div class="input-group-text"><i class="fa fa-key text-info"></i></div>

</div>

<input type="password" class="form-control" id="password" name="password" placeholder="your password here" required>

</div>

</div>

<div class="text-center">

<input type="submit" value="Login" name="login" class="btn btn-info btn-block rounded-0 py-2">

</div>

</form>

</div>

</div>

</div>

</div>

<?php }?>

</div>

</head>

<body>

</body>

</html>

<?php

$conn->close();

?>

```

The admin page will ask login credentials first then it will look like following screenshot:

![Admin Send Notifiv=cation to subscribers](https://www.w3school.info/blogimages/admin_web_push_page.png)

Now in your project if you open index.php you have a frontend where user will register themselves to receive notifications, and admin.php is your backend where you can send notifications to users or subscribers

If you face any problem in setup this small project please just let me know in the comments below, or by messaging me.

4706 views · 1 years ago

![Laravel Eloquent Relationship Part 1](https://images.ctfassets.net/vzl5fkwyme3u/2iNUlfYJ8SZVYUSemRAszt/eeb78994b12f1491f654d77026ab6c33/AdobeStock_199075029.png?w=1000)

Laravel introduces eloquent relationships from laravel 5.0 onwards. We all know, while we creating an application we all have foreign keys. Each table will be connected to some other. Eloquent make easy to connect each tables easily. Here we will One to one, one to many and many to many relationships. Here we will see three types of relationships,

1. One to one relationships

2. One to many relationships

3. Many to many relationships

## Why Eloquent Relationships

Here we have 2 tables, students and marks, so for join each table,

```php

$student = student::join(‘marks’,’marks.student_id,’=’,students.id’)->where(‘students.id’,’1’)->get();

dd($student);

```

the above query is to long, so when we connect more tables its too tough we will be having a big query and complicated.

## Model Query using Relationships

```php

$student_marks = student::find(1);

dd($student_marks->mark1);

```

The above example is a simple example of eloquent relationships. We can reduce the first query into a simple one.

### ONE TO ONE RELATIOSHIPS

Here we are creating 2 tables:

* Users

* Phones

Now we can see one to one relationships using `hasone()` and `belongsto()`.

We need to create table using migrations

#### Create migrations

users table will be created by using

```

Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

```

Phones table will be created by

```

Schema::create('phones', function (Blueprint $table) {

$table->increments('id');

$table->integer('user_id')->unsigned();

$table->string('phone');

$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

});

```

After that we need to create model for each tables, as we all know if the table name is laravel table name will be ending with ‘s’ and model name will be without ‘s’ of the same table name.

#### User model

```php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

{

use Notifiable;

protected $fillable = [

'name', 'email', 'password',

];

protected $hidden = [

'password', 'remember_token',

];

public function phone()

{

return $this->hasOne('App\Phone');

}

}

```

#### Phone Model

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model

{

/ **

* Get the user that owns the phone.

*/

public function user()

{

return $this->belongsTo('App\User');

}

}

```

#### For Creating records

```php

$user = User::find(1);

$phone = new Phone;

$phone->phone = '9080054945';

$user->phone()->save($phone);

$phone = Phone::find(1);

$user = User::find(10);

$phone->user()->associate($user)->save();

```

Now we can get our records by

```php

$phone = User::find(1)->phone;

dd($phone);

$user = Phone::find(1)->user;

dd($user);

```

### ONE TO MANY RELATIONSHIPS

Here we will use `hasMany()` and `belongsTo()` for relationships

Now we are creating two tables, posts and comments, we will be having a foreign key towards posts table.

Migrations for posts and comments table

```

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Schema::create('comments', function (Blueprint $table) {

$table->increments('id');

$table->integer('post_id')->unsigned();

$table->string("comment");

$table->timestamps();

$table->foreign('post_id')->references('id')->on('posts')

->onDelete('cascade');

});

```

Now we will create Post Model and Comment Model

#### Post Model

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

public function comments()

{

return $this->hasMany(Comment::class);

}

}

```

#### Comment Model

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model

{

public function post()

{

return $this->belongsTo(Post::class);

}

}

```

Now we can create records

```php

$post = Post::find(1);

$comment = new Comment;

$comment->comment = "Hi Harikrishnan";

$post = $post->comments()->save($comment);

$post = Post::find(1);

$comment1 = new Comment;

$comment1->comment = "How are You?";

$comment2 = new Comment;

$comment2->comment = "Where are you?";

$post = $post->comments()->saveMany([$comment1, $comment2]);

$comment = Comment::find(1);

$post = Post::find(2);

$comment->post()->associate($post)->save();

```

Now we can get records

```php

$post = Post::find(1);

$comments = $post->comments;

dd($comments);

$comment = Comment::find(1);

$post = $comment->post;

dd($post);

```

### MANY TO MANY RELATIONSHIPS

Many to many is little bit different and complicated than the above two.

In this example, I will create users, roles, and role, users_tables, here each table will be connected each other using the foreign keys.

Using `belongsToMany()` we will use see a demo of Many to many relationship

#### Create Migrations

```

Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

Schema::create('roles', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->timestamps();

});

Schema::create('role_user', function (Blueprint $table) {

$table->integer('user_id')->unsigned();

$table->integer('role_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

$table->foreign('role_id')->references('id')->on('roles')

->onDelete('cascade');

});

```

#### Create Models

**User Model**

```php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

{

use Notifiable;

/ **

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'email', 'password',

];

/ **

* The attributes that should be hidden for arrays.

*

* @var array

*/

protected $hidden = [

'password', 'remember_token',

];

/ **

* The roles that belong to the user.

*/

public function roles()

{

return $this->belongsToMany(Role::class, 'role_user');

}

}

```

**Role Model**

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model

{

public function users()

{

return $this->belongsToMany(User::class, 'role_user');

}

}

```

**UserRole Model**

```php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserRole extends Model

{

}

```

Now we can create records

```php

$user = User::find(2);

$roleIds = [1, 2];

$user->roles()->attach($roleIds);

$user = User::find(3);

$roleIds = [1, 2];

$user->roles()->sync($roleIds);

$role = Role::find(1);

$userIds = [10, 11];

$role->users()->attach($userIds);

$role = Role::find(2);

$userIds = [10, 11];

$role->users()->sync($userIds);

```

Now we can retrieve records

```php

$user = User::find(1);

dd($user->roles);

$role = Role::find(1);

dd($role->users);

```

Hence laravel Eloquent is more powerful and we do relationships easily compared to native query. We will be having three more relationships in laravel. Ie.., has many, one to many polymorphic and many to many polymorphic. With eloquent relationship we can easily connect the tables each other. One to one relationships we can connect two tables with their basic functionalities. In one to many we will connect with single table with multiple options. In Many to many we will be having more tables.

4409 views · 1 years ago

![Create Alarm and Monitoring on Custom Memory and Disk Metrics for Amazon EC2](https://images.ctfassets.net/vzl5fkwyme3u/2HgdCq2lZucMyuiYyYiQie/b7376c29a2f94799613e8c1cb8ff4d3b/AdobeStock_91111530.jpeg?w=1000)

Today I am going write a blog on how to Monitor Memory and Disk custom metrics and creating alarm in Ubuntu.

To do this, we can use Amazon CloudWatch, which provides a flexible, scalable and reliable solution for monitoring our server.

Amazon Cloud Watch will allow us to collect the custom metrics from our applications that we will monitor to troubleshoot any issues, spot trends, and configure operational performance. CloudWatch functions display alarms, graphs, custom metrics data and including statistics.

## Installing the Scripts

Before we start installing the scripts for monitoring, we should install all the dependent packages need to perform on Ubuntu.

First login to your AWS server, and from our terminal, install below packages

```ssh

sudo apt-get update

sudo apt-get install unzip

sudo apt-get install libwww-perl libdatetime-perl

```

### Now Install the Monitoring Scripts

Following are the steps to download and then unzip we need to configure the Cloud Watch Monitoring scripts on our server:

**1. In the terminal, we need to change our directory and where we want to add our monitoring scripts.**

**2. Now run the below command and download the source:**

```ssh

curl https://aws-cloudwatch.s3.amazonaws.com/downloads/CloudWatchMonitoringScripts-1.2.2.zip -O

```

**3. Now uncompress the currently downloaded sources using the following commands**

```ssh

unzip CloudWatchMonitoringScripts-1.2.2.zip && \

rm CloudWatchMonitoringScripts-1.2.2.zip && \

cd aws-scripts-mon

```

The directory will contain Perl scripts, because of the execution of these scripts only report memory run and disk space utilization metrics will run in our Ubuntu server.

Currently, our folder will contain the following files:

**mon-get-instance-stats.pl** - This Perl file is used to displaying the current utilization statistics reports for our AWS instance on which these file scripts will be executed.

**mon-put-instance-data.pl** - This Perl script file will be used for collecting the system metrics on our ubuntu server and which will send them to the Amazon Cloud Watch.

**awscreds.template** - This Perl script file will contain an example for AWS credentials keys and secret access key named with access key ID.

**CloudWatchClient.pm** - This Perl script file module will be used to simplify by calling Amazon Cloud Watch from using other scripts.

**LICENSE.txt** – This file contains the license details for Apache 2.0.

**NOTICE.txt** – This file contains will gives us information about Copyright notice.

**4. For performing the Cloud Watch operations, we need to confirm that whether our scripts have corresponding permissions for the actions:**

If we are associated with an IAM role with our EC2 Ubuntu instance, we need to verify that which will grant the permissions to perform the below-listed operations:

```ssh

cloudwatch:GetMetricStatistics

cloudwatch:PutMetricData

ec2:DescribeTags

cloudwatch:ListMetrics

```

Now we need to copy the ‘awscreds.template’ file into ‘awscreds.conf’ by using the command below and which will update the file with details of the AWS credentials.

```ssh

cp awscreds.template awscreds.conf

AWSAccessKeyId = my_access_key_id

AWSSecretKey = my_secret_access_key

```

Now we completed the configuration.

## mon-put-instance-data.pl

This Perl script file will collect memory, disk space utilization data and swap the current system details and then it makes handling a remote call to Amazon Cloud Watch to reports details to the collected cloud watch data as a custom metrics.

We can perform a simple test run, by running the below without sending data to Amazon CloudWatch

```ssh

./mon-put-instance-data.pl --mem-util --verify --verbose

```

Now we are going to set a cron for scheduling our metrics and we will send them to Amazon CloudWatch

**1. Now we need to edit the crontab by using below command:**

```ssh

crontab -e

```

**2. Now we will update the file using the following query which will disk space utilization and report memory for particular paths to Amazon CloudWatch in every five minutes:**

```ssh

*/5 * * * * ~/STORAGE/cloudwatch/aws-scripts-mon/mon-put-instance-data.pl --mem-util --mem-avail --mem-used --disk-space-util --disk-space-avail --disk-space-used --disk-path=/ --disk-path=/STORAGE --from-cron

```

If there is an error, the scripts will write an error message in our system log.

### Use of Options

**--mem-used**

The above command will collect the information about used memory and which will send the details of the reports in MBs into the MemoryUsed metrics. This will give us information about the metric counts memory allocated by applications and the OS as used.

**--mem-util**

The above command will collect the information about memory utilization in percentages and which will send the details of the Memory Utilization metrics and it will count the usage of the memory applications and the OS.

**--disk-space-util**

The above command will collect the information to collect the current utilized disk space and which will send the reports in percentages to the DiskSpaceUtilization for the metric and for the selected disks.

**--mem-avail**

The above command will collect the information about the available memory and which will send the reports in MBs to the MemoryAvailable metrics details. This is the metric counts memory allocated by the applications and the OS as used.

**--disk-path=PATH**

The above command will collect the information and will point out the which disk path to report disk space.

**--disk-space-avail**

The above command will collect the information about the available disk space and which will send the reports in GBs to the DiskSpaceAvailable metric for the selected disks.

**--disk-space-used**

The above command will collect the information about the disk space used and which will send the reports in GBs to the DiskSpaceUsed metric for the selected disks.

The PATH can specify to point or any of the files can be located on which are mounted point for the filesystem which needs to be reported.

If we want to points to the multiple disks, then specify both of the disks like below:

```ssh

--disk-path=/ --disk-path=/home

```

## Setting an Alarm for Custom Metrics

Before we are going to running our Perl Scripts, then we need to create an alarm that will be listed in our default metrics except for the custom metrics. You can see some default metrics are listed in below image:

![](https://4.bp.blogspot.com/-dYiNgtv5t4Q/XB-Kw76S49I/AAAAAAAAExM/DKKgzPUmVPUNpDqb0c57sVd3DjhY_3O6wCLcBGAs/s1600/aws.jpg)

Once we completed setting the cron, then the custom metrics will be located in Linux System Metrics.

Now we are going to creating the alarm for our custom metrics

**1. We need to open the cloudwatch console panel at https://console.aws.amazon.com/cloudwatch/home**

**2. Now navigate to the navigation panel, we need to click on Alarm and we can Create Alarm.**

**3. This will open a popup which with the list of the CloudWatch metrics by category.**

**4. Now click on the Linux System Metrics . This will be listed out with custom metrics you can see in the below pictures**

![](https://3.bp.blogspot.com/-3OxSPmHahYc/XB-MhlaGSAI/AAAAAAAAExY/d9UIOFakcGAOADlbNOyd75r0Vkl5GtOfwCLcBGAs/s1600/aws2.jpg)

![](https://2.bp.blogspot.com/-Urfud3sv5LA/XB-My0O-qXI/AAAAAAAAExg/1isOeglXYyoS3U0u2uhwJN8ddhtnoHUwACLcBGAs/s1600/aws3.jpg)

![](https://2.bp.blogspot.com/-tXU4ieWKKdo/XB-NDrArsII/AAAAAAAAExo/7oz3qQZ7GrMETiJwWJdK75_hJ0qfADLvgCLcBGAs/s1600/aws4.jpg)

**5. Now we need to select metric details and we need to click on the NEXT button. Now we need to navigate to Define Alarm step.**

![](https://3.bp.blogspot.com/-Vu0WoCCP_5o/XB-NiKGzmSI/AAAAAAAAExw/IPBX8ir-97Q_Q6L6Ajq2vNpukYGN8BB_QCLcBGAs/s1600/aws5.jpg)

**6. Now we need to define an Alarm with required fields**

Now we need to enter the Alarm name for identifying them. Then we need to give a description of our alarm.

Next, we need to give the condition with the maximum limit of bytes count or percentage when it notifies the alarm. If the condition satisfies, then the alarm will start trigger.

We need to provide a piece of additional information about for our alarm.

We need to define what are the actions to be taken when our alarm changes it state.

We need to select or create a new topic with emails needed for sending notification about alarm state.

**7. Finally, we need to choose the Create Alarm.**

So its completed. Now the alarm is created for our selected custom metrics.

### Finished!

Now the alarm will be listed out under the selected state in our AWS panel. Now we need to select an alarm from the list seen and we can see the details and history of our alarm.

    SPONSORS