Model relations and Querying Laravel

Posts model may look like below

    public function tags(){
        return $this->hasMany('App\Models\Posttag','post_id','post_id');
    }
    public function user(){
        return $this->belongsTo('App\Models\User','user_id');
    }
    public function comments(){
        return $this->hasMany('App\Models\Comment','post_id','post_id');
    }
    public function comments_count(){
        return $this->hasOne('App\Models\Comment','post_id','post_id')->selectRaw('post_id, count(*) as aggregate')->groupBy('post_id');
    }

Then we can query data like so

	   $data = Post::with(['tags','comments' => function($query){
			$query->with(array('owner'))->orderBy('created_at','DESC')->limit(1);
			},'user' => function($query){
                                  $query->select('id','name','profile_pic');
                       }])->get();
Advertisements

Update url parameter jquery

function setGetParameter(paramName, paramValue)
    {
            var url = window.location.href;
            var hash = location.hash;
            url = url.replace(hash, '');
            if (url.indexOf(paramName + "=") >= 0)
            {
                var prefix = url.substring(0, url.indexOf(paramName));
                var suffix = url.substring(url.indexOf(paramName));
                suffix = suffix.substring(suffix.indexOf("=") + 1);
                suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
                url = prefix + paramName + "=" + paramValue + suffix;
            }
            else
            {
            if (url.indexOf("?") < 0)
                url += "?" + paramName + "=" + paramValue;
            else
                url += "&" + paramName + "=" + paramValue;
            }
            window.location.href = url + hash;
    }

Drawing on google maps

Dummy marker.sql


CREATE TABLE IF NOT EXISTS `markers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `address` varchar(80) NOT NULL,
  `lat` float(10,6) NOT NULL,
  `lng` float(10,6) NOT NULL,
  `image` text NOT NULL,
  `type` varchar(125) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1  ;



INSERT INTO `markers` ( `name`, `address`, `lat`, `lng`, `image`, `type`) VALUES
( 'Pan Africa Market', '1521 1st Ave, Seattle, WA', 47.608940, -122.340141, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Buddha Thai & Bar', '2222 2nd Ave, Seattle, WA', 47.613590, -122.344391, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'The Melting Pot', '14 Mercer St, Seattle, WA', 47.624561, -122.356445, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Ipanema Grill', '1225 1st Ave, Seattle, WA', 47.606365, -122.337654, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Sake House', '2230 1st Ave, Seattle, WA', 47.612823, -122.345673, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'Crab Pot', '1301 Alaskan Way, Seattle, WA', 47.605961, -122.340363, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Mama''s Mexican Kitchen', '2234 2nd Ave, Seattle, WA', 47.613976, -122.345467, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'Wingdome', '1416 E Olive Way, Seattle, WA', 47.617214, -122.326584, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'Piroshky Piroshky', '1908 Pike pl, Seattle, WA', 47.610126, -122.342834, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant');


phpsqlajax_genxml.php


$username="ab";   //db username
$password="ab";    //db password
$database="ab";    // database name

$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);

// Opens a connection to a MySQL server

$connection=mysql_connect ('localhost', $username, $password);
if (!$connection) {  die('Not connected : ' . mysql_error());}

// Set the active MySQL database

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

// Select all the rows in the markers table

$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}

header("Content-type: text/xml");

// Iterate through the rows, adding XML nodes for each

while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  $node = $dom->createElement("marker");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("name",$row['name']);
  $newnode->setAttribute("address", $row['address']);
  $newnode->setAttribute("lat", $row['lat']);
  $newnode->setAttribute("lng", $row['lng']);
  $newnode->setAttribute("image", $row['image']);
  $newnode->setAttribute("type", $row['type']);
}

echo $dom->saveXML();

Maps.html


<script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_BROWSER_KEY_HERE&libraries=places,drawing,geometry"
            type="text/javascript"></script>
<script type="text/javascript">
var markers = [];
	var markersToRemove = [];
	var ploy;
	var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      }
    };
    //function called on body load
    function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(47.6145, -122.3418),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
	  
	  
	  /****controlss *********************************/
	  
	  
	  var drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_CENTER,
            drawingModes: [
            google.maps.drawing.OverlayType.POLYGON,
            ]
        },
        markerOptions: {
            icon: 'images/beachflag.png'
        },
        circleOptions: {
            fillColor: '#ffff00',
            fillOpacity: 1,
            strokeWeight: 5,
            clickable: false,
            editable: true,
            zIndex: 1
        },
		
    });
    drawingManager.setMap(map);
	google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
		 for(var i = 0; i < markersToRemove.length; i++) {
			markersToRemove[i].setMap(null);
		}
		polyOptions  = event.overlay.getPath().getArray();   //get coordinates of polygon
		
		var poly = new google.maps.Polygon({
				paths : polyOptions,
				strokeColor: '#FF0000',
				strokeOpacity: 0.8,
				strokeWeight: 2,
				fillColor: '#FF0000',
				fillOpacity: 0.35,
				});  //get polygon using its coordinates
		downloadUrl("phpsqlajax_genxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
		document.getElementById("content_list").innerHTML = "";
        for (var i = 0; i < markers.length; i++) {
                        //get our marker points from database
			var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
			console.log(google.maps.geometry.poly.containsLocation(point,poly));
			 if(google.maps.geometry.poly.containsLocation(point,poly)) { // check if marker point is inside polygon drawn
						var m = new google.maps.Marker({
							position: point,
							map: map
						});
						
						/************create list in sidebar again and render new list in sidebar*******/
						 var infoWin = new google.maps.InfoWindow;
						  var name = markers[i].getAttribute("name");
						  var address = markers[i].getAttribute("address");
						  var type = markers[i].getAttribute("type");
						  var image = markers[i].getAttribute("image");
						  var point = new google.maps.LatLng(
							  parseFloat(markers[i].getAttribute("lat")),
							  parseFloat(markers[i].getAttribute("lng")));
						  var html = "<b>" + name + "</b> <br/>" + address;
						  var icon = customIcons[type] || {};
						  bindInfoWindow(m, map, infoWin, html);
						  var listt = createSidebarEntry(m, name, address, image);
						  document.getElementById("content_list").appendChild(listt);
						
						/**************list in sidebar******************/
			}	
        }
      });

				//add clear overlay button on overlaycomplete,not sure if it is working
				var controlDiv = document.getElementById("control-div");
				var controlUI = document.getElementById("control-ui");
				var controlText = document.getElementById("control-text");
				controlUI.click(function() {
					map.setZoom(11);
				 });
				map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
				
	});

  
   
   
	  
	  
	  
	  
	  /**********controls ****************************/
	  
	  
	  
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("phpsqlajax_genxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
		  var image = markers[i].getAttribute("image");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
		  markersToRemove.push(marker);
          bindInfoWindow(marker, map, infoWindow, html);
		  var listt = createSidebarEntry(marker, name, address, image);
		  document.getElementById("content_list").appendChild(listt);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}
//create sidebar entry for properties
function createSidebarEntry(marker, name, address, image) {
      var div = document.createElement('div');
	  var html ='<div class="images"><img src ="'+image+'" class="images_property" height="100px" width="100px"/></div>';
      html += '<div class="content"><b class="title">' + name + '</b><p class="address">' + address + '</p></div>';
      div.innerHTML = html;
	  div.className = "list_item";
      div.style.cursor = 'pointer';
	  div.style.float = 'left';
	  div.style.width = '100%';
      div.style.marginBottom = '5px'; 
	  google.maps.event.addDomListener(div, 'click', function() {
        google.maps.event.trigger(marker, 'click');
      });
     return div;
    }
</script>

 <body onload="load()">
  <div class="container">
    <div id="map" style="width: 60%; height: 800px;float:left;"></div>
	<div id="content_list" style="width: 40%; height: 800px;float:left;overflow: auto;"></div>
	</div>
</body>
.list_item {
     cursor: pointer;
    float: left;
    height: 110px;
    margin-bottom: 5px;
    width: 100%;
}
.images {
    float: left;
    height: 100px;
}

.content {
    float: left;
    height: 100px;
	padding:5px;
}
.title{
color :#0074e4;
font-size:15px;
}
.address{
color :#666;
}
.top{
	position: absolute;
    transition: width 0.3s ease 0s;
    z-index: 21;
}

Before drawing map looks like

google_maps_all_list

After drawing map looks like

google_maps

Simple CRUD operations with file upload ruby on rails

The controller file

class WelcomeController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  def index
  	
  end
  def list
  	@tweets = Tweet.all
  end
  def save

	upload = params[:upload]
        name =  upload['datafile'].original_filename
	directory = "public/tweet_files"
	# create the file path
	path = File.join(directory, name)
        # write the file
	File.open(path, "wb") { |f| f.write(upload['datafile'].read) }

  	t = Tweet.new
	t.title = params[:title]
	t.tweet = params[:tweet]
	t.file = name
	t.save
        
        

        flash[:notice] = "Tweet saved!"
        redirect_to :action => 'list'
  end
  def new
  end
  def edit
       @tweet = Tweet.find(params[:id])
       
  end
  def delete
       t = Tweet.find(params[:id])
       t.destroy
       flash.keep[:notice] = "Tweet deleted!"
       redirect_to :action => 'list'
  end
 def update
	upload = params[:upload]
        name =  upload['datafile'].original_filename
	directory = "public/tweet_files"
	# create the file path
	path = File.join(directory, name)
        # write the file
	File.open(path, "wb") { |f| f.write(upload['datafile'].read) }

       t = Tweet.find(params[:id])
       t.title = params[:title]
       t.tweet = params[:tweet]
       t.file = name
       t.save
       flash.keep[:notice] = "Tweet updated!"
       redirect_to :action => 'list'
  end
end

view files list.html.erb

<style>
table{
border-collapse: collapse;
    font-family: "Trebuchet MS",Arial,Helvetica,sans-serif;
    width: 100%;
}
table, td, th {
    border: 1px solid green;
    text-align:center;
}

th {
    background-color: green;
    color: white;
    font-weight:bold;
}
</style>
<%= notice %><br>
<%= link_to "Add new",:controller => :welcome, :action => :new %>
<br>
<table>
<thead><tr><th>Title</th><th>Tweet</th><th>Image</th><th>Edit</th><th>Delete</th></tr></thead>
<tbody>
<% @tweets.each do |tweet| %>
<tr>
 <td><%=  tweet.title %></td>
 <td><%=  tweet.tweet %></td>
<td><%=  image_tag("/tweet_files/#{tweet.file}") %></td>
<td><%= link_to "Edit",:controller => :welcome, :action => :edit ,:id => tweet.id %> </td>
<td><%= link_to "Delete",:controller => :welcome, :action => :delete,:id => tweet.id  %> </td>
</tr>
<% end %>
</tbody>
<% if @tweets.size == 0 %>
<em>No tweets found</em>
<% end %>


edit.html.erb


<%= form_tag({controller: "welcome", action: "update"}, method: "post",multipart: true) do %>
  <%= label_tag(:tweet, "Update Tweet") %>
 <br>
 
  <%= text_field_tag "title" , @tweet.title %> 
<br>
 
  <%= text_field_tag "tweet" , @tweet.tweet %>
<br>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
<%=  image_tag("/tweet_files/#{@tweet.file}") %>
  <%= submit_tag("update") %>
<% end %>


new.html.erb


<%= form_tag({controller: "welcome", action: "save"}, method: "post",multipart: true) do %>
  <%= label_tag(:tweet, "Add Tweet") %>
<br>
  <%= text_field_tag "title" %>
<br>
  <%= text_field_tag "tweet" %>
<br>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
  <%= submit_tag("Save") %>
<% end %>



routes.rb

   root 'welcome#list'
   post 'welcome/save' => 'welcome#save'
   get  'welcome/new'  => 'welcome#new'
   get  'welcome/edit/:id'  => 'welcome#edit'
   get  'welcome/delete/:id'  => 'welcome#delete'
   post  'welcome/update/:id'  => 'welcome#update'

Here is how to add migrations to active records…adding column file here

$ rails generate migration add_file_to_tweets file:string
$ rake db:migrate

Here is how to create folder

cd myrailsproject
cd public
mkdir tweet_files

Setting up an application with mysql database on rails server on ubuntu 14.04

Simple steps to be followed
I assume you have installed rails, ruby gems and mysql

1) Create a new application with mysql database.

— name of application : myapplication
— db driver mysql

	$ rails new myapplication -d mysql
        

2) Run your application on rails server

CD to myapplication

	$ rails server
       

3) Create a database for the application
CD to myapplication

	$ rails db
        

Enter the password for root user

	mysql> create database mydb;
	mysql> create user abc identified by 'PASSWORD';
	mysql> grant all privileges on mydb.* to abc@localhost identified by 'PASSWORD';
	mysql>quit
	

4) Now place the username,password and database name in database.yml file under config folder of your app.
5) Goto routes.rb
— uncomment root ‘welcome#index’

6) Create a controller class welcome_controller.rb under controller folder and add an action index to it.

	class WelcomeController < ApplicationController
		def index
		end
	end
        

7) Create a view file for function index under views/welcome/index.html.erb
write

<h1>Hello Rails</h1>

to view file.
8) Now run the rails server as
CD to myapplication

   $ rails server
  

open in browser —> localhost:3000

You will see Hello Rails in browser window.

Upload image plus all form data using jquery

Html

<form action="" method="post" enctype="multipart/form-data" id="form_portfolio_save">
				<input type="text" name="title" id="title" placeholder=""/><br/>
				<textarea id="about_project" name="about_project">About project</textarea><br/>
				<input type="file" name="photo" id="port_image" placeholder="Add Files"/><br/>
				<input type="text" name="caption" id="caption" placeholder="Image caption"/><br/>
				<input type="button" id="submit" value="Submit" class="button submit" onclick="save_portfolio();return false;"/>
				<input type="button" class="button cancel" id="submit" value="Cancel" />
			  </form>

JQuery

function save_portfolio(){
		var fd = new FormData();
		var file_data = $('input[name^="photo"]')[0].files; 
		for(var i = 0;i<file_data.length;i++){
			fd.append("file_"+i, file_data[i]);
		}
		var  other_data = $("#form_portfolio_save").serializeArray();
		 $.each(other_data,function(key,input){
			fd.append(input.name,input.value);
		});
	   
		$.ajax({
		url : 'save_portfolio.php',
		type : "post",
		data : fd,
		cache: false,
		contentType: false,
		processData: false,
		success : function(data){
				$("#append_portfolio").append(data);
				
		}
	});
	}

PHP

include("includes/session.php");
include("includes/database.php");
if(!empty($_FILES['file_0'])){
		$filename = time().$_FILES['file_0']['name'];
		$path= "upload/user_portfolio/".$filename;
		move_uploaded_file($_FILES['file_0']['tmp_name'],$path);
	}
$query = "insert into user_portfolio(title,description,images,image_captions,employee_id) values('".$_POST['title']."','".$_POST['about_project']."','".$filename."','".$_POST['caption']."','".$_SESSION['user_details']['id']."')";
mysql_query($query);