matildah

matildah

Member Since 7 Months Ago

Experience Points
1,760
Total
Experience

3,240 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
1,760 XP
Nov
18
11 hours ago
Activity icon

Replied to Route Not Defined Yet Defined

oh thank you for the tip

Activity icon

Started a new Conversation Route Not Defined Yet Defined

am trying to reference my homepage on a page called confirmation page.This is the route

Route::get('/', function () {
    $events = App\Event::all();
    return view('layouts.landing')->with('events',$events);
});

here is the link

<a id="go" href="{{route('/')}}">Go to homepage</a>

when i click on the link it says route not defined

Nov
13
5 days ago
Activity icon

Replied to If Statement Is True Even If Its Not When Saving Ticket

hey theres a problem it doesnt save ticket nor decrement even if the condition is true

Activity icon

Replied to If Statement Is True Even If Its Not When Saving Ticket

i will look into the race condition thanks alot

Activity icon

Replied to If Statement Is True Even If Its Not When Saving Ticket

yes it does theres a decrement below

Activity icon

Started a new Conversation If Statement Is True Even If Its Not When Saving Ticket

I have maximum number of attendees per event. When storing tickets, it still saves even when the number ordered exceeds the maximum.

store function:

public function store(Request $request){
    // Create Ticket
    $ticket=new Ticket;
    $ticket->userName= $request->input('userName');
    $ticket->userEmail= $request->input('userEmail');
    $ticket->phoneNumber= $request->input('phoneNumber');
    $ticket->regular_quantity= $request->input('regular_quantity');
    $ticket->vip_quantity= $request->input('vip_quantity');
    $ticket->event_id=$request->route('id');
    $ticket->total= $request->input('regular_quantity') + $request->input('vip_quantity');

    $event = Event::where('id',$ticket->event_id)->first();

    if($ticket->regular_quantity<$event->regular_attendies){
        DB::table('events')->decrement('regular_attendies', $ticket->regular_quantity);
    } else if($ticket->vip_quantity<$event->$vip_attendies){
        DB::table('events')->decrement('vip_attendies', $ticket->vip_quantity);  
    } else {
        return redirect ('/admin');
    }  

    $ticket->save();
    return redirect('/');
}         
Activity icon

Replied to How Can Update Stocks Table After Done A Sales

hey how can i pass the quantity ordered instead of 1

Activity icon

Started a new Conversation Prevent User From Ordering More Than The Placed Tickets

i have two tables events and tickets the.events table contains the number of people that are supposed to attend in a column Max_attendies This is the store function for ticket

$ticket=new Ticket;
      $ticket->userName= $request->input('userName');
      $ticket->userEmail= $request->input('userEmail');
      $ticket->phoneNumber= $request->input('phoneNumber');
      $ticket->regular_quantity= $request->input('regular_quantity');
      $ticket->vip_quantity= $request->input('vip_quantity');
      $ticket->event_id=$request->route('id');
      $ticket->total= $request->input('regular_quantity') + $request->input('vip_quantity');

ticket also stores the event id .i've created the relationships already

  public function tickets(){
          return $this->hasMany(Ticket::class);
        }
public function events(){
        return $this->belongsTo(Event::class);
    }

someone help me with the query am stuck am new with SQL

Activity icon

Replied to Update Two Tables In A Store Function

when the store function is executed i want to store the elements in events nd seats table

Activity icon

Started a new Conversation Update Two Tables In A Store Function

i have two tables events and tickets

Schema::create('tickets', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('userEmail');
            $table->string('userName');
            $table->integer('phoneNumber');
            $table->integer('regular_quantity');
            $table->integer('vip_quantity');
            $table->integer('event_id');
$table->integer('booked_tickets');
        });

events

 $table->bigIncrements('id');
            $table->timestamps();
            $table->string('eventName');
            $table->string('details');
            $table->string('location');
            $table->integer('Max_attendies');
            $table->integer('regularPrice');
            $table->integer('VIP_price');

This is the store function for tickets

 // Create Ticket
      $ticket=new Ticket;
      $ticket->userName= $request->input('userName');
      $ticket->userEmail= $request->input('userEmail');
      $ticket->phoneNumber= $request->input('phoneNumber');
      $ticket->regular_quantity= $request->input('regular_quantity');
      $ticket->vip_quantity= $request->input('vip_quantity');
      $ticket->event_id=$request->route('id');
      $ticket->save();

Relationship

public function tickets(){
          return $this->hasMany(Ticket::class);
        }
 public function events(){
        return $this->belongsTo(Event::class);
    }

i need when a user stores a ticket the column booked seats in events table is updated by adding regular_quantity and vip_quantity

Nov
10
1 week ago
Activity icon

Replied to Target Class [App\Http\Controllers\EventsController] Does Not Exist

thanks i've seen where the problem is the typo

Activity icon

Started a new Conversation Target Class [App\Http\Controllers\EventsController] Does Not Exist

theres a create button on my admin page where its supposed to open the create page

<a href="{{route('create')}}">Add Event</a>

My controller function to create open this is

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Event;

class EventsContoller extends Controller{

public function create()
    {
        return view('layouts.create');
    }
}

My web.php route is

Route::get('/admin/create', '[email protected]')->name('create');

i've tried composer dumpautoload but its not working

Nov
09
1 week ago
Activity icon

Started a new Conversation Populating Database With Image Using Tinker

whats the tinker command of uploading an image?

Nov
01
2 weeks ago
Oct
31
2 weeks ago
Activity icon

Started a new Conversation Show Auth Errors When Login And Register Are In One Page(Jquery Tabs)

My login and registration form are in one index page which the user switches through them using jquery

<script>
   
        $('#reg').hide();
       
        $('#btn-login').click(function(){
            $('#reg').hide();
            $('#lgn').show();
        });
        $('#btn-register').click(function(){
            $('#lgn').hide();
            $('#reg').show();
        });
        </script>

But when there errors on the registration page the page loads to login page first but i want it to load to active tab

<form method="POST" action="{{ route('login')}}" autocomplete="off">
            @csrf
            @if($errors->any()) 
            <div class="auth-error">
            <i class="icon-warning-sign"></i>Error:Incorrect password/email.Please try again
            </div>
          @endif
            <div class="textbox">
                <i class="icon-envelope"></i>
                <input type="email"  placeholder="Email" name="email" class="inputs">  
            </div>
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <div class="textbox">
                    <i class="icon-lock" ></i>
                <input type="password"  placeholder="Password" name="password" value="" class="inputs" autocomplete="new-password" >
               
           
            </div>
            <a class="forgot" href="{{ route('password.update') }}">Forgot password?</a>
            <input type="submit" value="Login" class="submit-buttons">
            
        </form>
</div>
<div id="reg" class="btns">
    <span class="logo">
        <h5>Task<font color="#F4D03F ">Weekly</font></h5>
        </span>
       
    <p>Create account</p><br>
    <p style="font-size:20px">Fill in your details to start using TaskWeekly</p>
    <form action="{{route('register')}}" method="POST">
        @if (count($errors) > 0)
        @foreach ($errors->all() as $error)
          <p >{{ $error }}
          </button>
        </p>
        @endforeach
      @endif
        <div class="textbox">
            <i class="icon-user"></i>
            <input type="name" placeholder="Username" name="name"  class="inputs">
            
                 </div>
        <div class="textbox">
            <i class="icon-envelope"></i></i>
        <input type="email" placeholder="Email" name="email"  class="inputs">
    
    </div>

        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <div class="textbox">
                <i class="icon-lock"></i>
            <input type="password" placeholder="Password" name="password"  class="inputs" autocomplete="new-password">
        
        </div>
        
        <div class="textbox">
            <i class="icon-lock"></i>
        <input type="password" placeholder="confirm password"name="password_confirmation" value="" class="inputs">
    </div>
   
    <input type="submit" value="Register" class="submit-buttons" id="register">
    </form>  
</div> {{--End of auth-card--}}
</div>
</div>
Activity icon

Replied to Redirecting Back To A Specific Div Section With Validation Errors

do i have to use the bootstrap tabs or what does tab mean

Oct
30
2 weeks ago
Activity icon

Replied to Redirecting Back To A Specific Div Section With Validation Errors

hey am not using ajax just jquery

Activity icon

Started a new Conversation Redirecting Back To A Specific Div Section With Validation Errors

I have a page which has two divs which holds the login form and registration form

<div class="main">
    <div class="auth-buttons" >
        <a class="btn" id="btn-login">Login</a>
        <a class="btn" id="btn-register">Register</a>
    </div>
    <div id="lgn" class="btns">
        <form>
        </form>
    </div>
    <div id="reg" class="btns">
        <form>
        </form>
    </div>
</div>

i have jquery which switches between the login and register

<script>
    $('#reg').hide();
    $('#btn-login').click(function() {
        $('#reg').hide();
        $('#lgn').show();
    });
    $('#btn-register').click(function() {
        $('#lgn').hide();
        $('#reg').show();
    });

But when the register form has errors the form loads to the first page which is login how to i redirect to registration div with the errors?

here is what i tried it shows the errors on the registration form but it first loads the login form i want it to directly load the regstration tab with errors

if ( $validator->fails() ) {
    return redirect(url()->previous() .'#reg')->withErrors($validator)->withInput();
}
</script>
Oct
29
2 weeks ago
Activity icon

Started a new Conversation Redirecting Back To A Specific Div Section With Validation Errors

I have a page which has two divs which holds the login form and registration form

<div class="main">
    <div class="auth-buttons" >
        <a class="btn" id="btn-login">Login</a>
        <a class="btn" id="btn-register">Register</a>
    </div>
    <div id="lgn" class="btns">
        <form>
        </form>
    </div>
    <div id="reg" class="btns">
        <form>
        </form>
    </div>
</div>

i have jquery which switches between the login and register

<script>
    $('#reg').hide();
    $('#btn-login').click(function() {
        $('#reg').hide();
        $('#lgn').show();
    });
    $('#btn-register').click(function() {
        $('#lgn').hide();
        $('#reg').show();
    });
</script>

But when the register form has errors the form loads to the first page which is login how to i redirect to registration div with the errors?

here is what i tried but it didnt work

if ( $validator->fails() ) {
    return redirect(url()->previous() .'#reg')->withErrors($validator)->withInput();
}
Oct
17
1 month ago
Activity icon

Replied to Calculation Of Progress Of That Particular Week

what about the tasks the user kept from last week they'll still calculate

Activity icon

Started a new Conversation Calculation Of Progress Of That Particular Week

hey guys am working on a to do list web app and i want to incoporate progress feature where it shows the percentage in that particular week which will be calculated by tasks completed/tasks to be done *100 but i want it to be for that particular week how do i do it

Aug
28
2 months ago
Activity icon

Started a new Conversation Saving Cart Items To Cart

These are the cart details

    $cart[$id] = [
            ,
            "name" => $food->food_item,
                "quantity" => 1,
                 "price" => $food->price,
                 "restaurant" =>$food->restaurant_id,
              ];

I want when the user clicks a button place order to save these item details in orders table in their respective fields

//create order order= new Order;

how will i save the cart?

Aug
27
2 months ago
Activity icon

Replied to Button Not Redirecting

stiil same problem but when i write

dd($food);

on the function it outputs the correct results

Activity icon

Started a new Conversation Button Not Redirecting

i have an order button that is supposed to redirect the user to the cart page with the items ordered

Order this

This is the route on web.php

Route::get('add-to-cart/{id}', '[email protected]')->name('addCart');

This is the function addToCart

public function addToCart($id){ $food = Food::find($id);

    if(!$food) {

        abort(404);

    }

    $cart = session()->get('cart');

    // if cart is empty then this the first product
    if(!$cart) {

        $cart = [
                $id => [
                    // "productId" => $food->id,
                    "name" => $food->food_item,
                    "quantity" => 1,
                    "price" => $food->price,

                ]
        ];


        session()->put('cart', $cart);


        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }

    // if cart not empty then check if this product exist then increment quantity
    if(isset($cart[$id])) {

        $cart[$id]['quantity']++;

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product added to cart successfully!');

    }

    // if item not exist in cart then add to cart with quantity = 1
    $cart[$id] = [
        // "productId" => $food->id,
        "name" => $food->food_item,
        "quantity" => 1,
        "price" => $food->price,

    ];


    session()->put('cart', $cart);

    return redirect()->back()->with('success', 'Product added to cart successfully!');
}

But when i click the button it doesn't redirect to the cart page it keeps loading to the same page

Aug
26
2 months ago
Activity icon

Started a new Conversation Laravel Cart Not Picking Up Food Price

Am building an ordering system for restaurants When one clicks order here it takes the user to the cart page.

but my cart page isn't displaying the food price.It displays it as 0 yet the price exists

Product Price Quantity Subtotal
    <?php $total = 0 ?>

    @if(session('cart'))
        @foreach(session('cart') as $id => $details)

            <?php $total += (int)$details['price'] *(int)$details['quantity'] ?>

            <tr>
                <td data-th="Product">
                    <div class="row">
                        {{-- <div class="col-sm-3 hidden-xs"><img src="{{ $details['photo'] }}" width="100" height="100" class="img-responsive"/></div> --}}
                        <div class="col-sm-9">
                            <h4 class="nomargin">{{ $details['name'] }}</h4>
                        </div>
                    </div>
                </td>
                <td data-th="Price">{{(int) $details['price'] }}</td>
                <td data-th="Quantity">
                    <input type="number" value="{{ $details['quantity'] }}" class="form-control quantity" />
                </td>
                <td data-th="Subtotal" class="text-center">{{(int) $details['price'] *(int) $details['quantity'] }}</td>
                <td class="actions" data-th="">
                    <button class="btn btn-info btn-sm update-cart" data-id="{{ $id }}"><i class="fa fa-refresh"></i></button>
                    <button class="btn btn-danger btn-sm remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
                </td>
            </tr>
        @endforeach
    @endif

    </tbody>
    <tfoot>
    <tr class="visible-xs">
        <td class="text-center"><strong>Total {{ $total }}</strong></td>
    </tr>
    <tr>
        <td><a href="{{ url('/') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
        <td colspan="2" class="hidden-xs"></td>
        <td class="hidden-xs text-center"><strong>Total ${{ $total }}</strong></td>
    </tr>
    </tfoot>
</table>

@endsection

Aug
24
2 months ago
Activity icon

Started a new Conversation Property [name] Does Not Exist On This Collection Instance In Restaurants Application

i have a restaurants controller and i want it to open the profile when you click on its link on all restaurants page

This is the show function

public function show($id) { $restaurant = Restaurant::find($id); return view('restaurants.profile')->with('restaurant', $restaurant); } This is the profile page

{{$restaurant->name }}

            </div>

am getting the error above

Aug
22
2 months ago
Activity icon

Replied to Display Most Rated Restaurants

jeffrey who

Aug
21
2 months ago
Activity icon

Started a new Conversation Display Most Rated Restaurants

Setup

i have restaurants table and reviews table with a relationship restaurants

  public function reviews(){
  return $this->hasMany('App\Review');
  }

reviews

public function restaurant(){
return $this->belongsTo('App\Restaurant');

}

i need to write a query to display most rated to least rated restaurants any help please

The reviews table stores the restaurant id too

Aug
20
2 months ago
Activity icon

Started a new Conversation Query Search From Two Related Tabels Using A Search Term 'q'

i have two tables food table and restaurants table which are all related by restaurant id

This is the relationship in the food models

public function restaurant(){ return $this->belongsTo('App\Restaurant'); }

This is the food table

$table->bigIncrements('id'); $table->timestamps(); $table->integer('price'); $table->integer('food_item'); $table->integer('restaurant_id');

This is the relationship in the restaurants model

public function foods(){ return $this->hasMany('App\Food'); }

Aug
19
2 months ago
Activity icon

Replied to Quering Restaurants According To Particular Food

am getting error Call to undefined method App\Restaurant::food()

Aug
18
3 months ago
Activity icon

Started a new Conversation Quering Restaurants According To Particular Food

I have a search input where users are supposed to searchso as to return results

<div class="field" id="searchform">

        <input type="text" id="searchterm" placeholder="e.g mutton 
        
        karahi,pizza..."  />
        
        <button type="button" id="search" 
        
        onclick="window.location='http://localhost:8000/search'">Find Food!</button>
        
        </div>

The food items are in a table called foods which has the following fields

$table->bigIncrements('id');
            $table->timestamps();
            $table->integer('price');
            $table->string('food_item')
            $table->integer('restaurant_id');
        });

The is a different table for restaurants where the foods table gets restaurant_id

How can go about this

Activity icon

Started a new Conversation How To Implement Restaurant Owner Registration

How will i implement restaurant owner registration in a restaurant finder where the owner can only change information of the restaurant he owns

Activity icon

Replied to How To Put A Link On Info Window

oh thank you lemme take a look at it

Activity icon

Started a new Conversation How To Put A Link On Info Window

i have a markers that are supposed to have an info window when you click it it takes you to restaurants profile.how do i go about it?

Activity icon

Started a new Conversation Call To Undefined Function Save()

public function store(Request $request) { $menu=new Menu; $menu->restaurant_id=$request->get('restaurant_id'); $menu->value=$request->input('food_item'); $menu->value=$request->input('price');

    $menu>save();
    return redirect('/restaurants')->withStatus(__('Restaurant successfully updated.'));
}

trying to save this menu getting the error above Call to undefined function save()

Activity icon

Started a new Conversation XML Not Displaying Anything

am following this tutorial https://developers.google.com/maps/documentation/javascript/adding-a-google-map

This is my xml file that is supposed to render the restaurants on the map

Aug
17
3 months ago
Activity icon

Started a new Conversation XML Not Displaying Results

ollowing this tutorial https://developers.google.com/maps/documentation/javascript/adding-a-google-map

am not getting any results.decided to put the code altogether didnt create a separate file

<!DOCTYPE html >
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>Creating a Store Locator on Google Maps</title>
  <style>
    /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
    #map {
      height: 100%;
    }
    /* Optional: Makes the sample page fill the window. */
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
 </style>
  </head>
  <body style="margin:0px; padding:0px;" onload="initMap()">
    
    <div>
         <label for="raddressInput">Search location:</label>
         <input type="text" id="addressInput" size="15"/>
        <label for="radiusSelect">Radius:</label>
        <select id="radiusSelect" label="Radius">
          <option value="50" selected>50 kms</option>
          <option value="30">30 kms</option>
          <option value="20">20 kms</option>
          <option value="10">10 kms</option>
        </select>

        <input type="button" id="searchButton" value="Search"/>
    </div>
    <div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
    <div id="map" style="width: 100%; height: 90%"></div>
    <script>
      var map;
      var restaurants = [];
      var infoWindow;
      var locationSelect;

        function initMap() {
        var juja = {lat:-1.1026, lng:37.0132};
          map = new google.maps.Map(document.getElementById('map'), {
            center: juja,
            zoom: 11,
            mapTypeId: 'roadmap',
            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
          });
          infoWindow = new google.maps.InfoWindow();

          searchButton = document.getElementById("searchButton").onclick = searchLocations;

          locationSelect = document.getElementById("locationSelect");
          locationSelect.onchange = function() {
            var restaurantNum = locationSelect.options[locationSelect.selectedIndex].value;
            if (restaurantNum != "none"){
              google.maps.event.trigger(restaurants[restaurantNum], 'click');
            }
          };
        }

       function searchLocations() {
         var address = document.getElementById("addressInput").value;
         var geocoder = new google.maps.Geocoder();
         geocoder.geocode({address: address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
            searchLocationsNear(results[0].geometry.location);
           } else {
             alert(address + ' not found');
           }
         });
       }

       function clearLocations() {
         infoWindow.close();
         for (var i = 0; i < restaurants.length; i++) {
           restaurants[i].setMap(null);
         }
         restaurants.length = 0;

         locationSelect.innerHTML = "";
         var option = document.createElement("option");
         option.value = "none";
         option.innerHTML = "See all results:";
         locationSelect.appendChild(option);
       }

       function searchLocationsNear(center) {
         clearLocations();

         var radius = document.getElementById('radiusSelect').value;
         var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
         downloadUrl(searchUrl, function(data) {
           var xml = parseXml(data);
           var restaurantNodes = xml.documentElement.getElementsByTagName("restaurant");
           var bounds = new google.maps.LatLngBounds();
           for (var i = 0; i < restaurantNodes.length; i++) {
             var id = restaurantNodes[i].getAttribute("id");
             var name = restaurantNodes[i].getAttribute("name");
             var address = restaurantNodes[i].getAttribute("address");
             var distance = parseFloat(restaurantNodes[i].getAttribute("distance"));
             var latlng = new google.maps.LatLng(
                  parseFloat(restaurantNodes[i].getAttribute("lat")),
                  parseFloat(restaurantNodes[i].getAttribute("lng")));

             createOption(name, distance, i);
             createRestaurant(latlng, name, address);
             bounds.extend(latlng);
           }
           map.fitBounds(bounds);
           locationSelect.style.visibility = "visible";
           locationSelect.onchange = function() {
             var restaurantNum = locationSelect.options[locationSelect.selectedIndex].value;
             google.maps.event.trigger(restaurants[restaurantNum], 'click');
           };
         });
       }

       function createRestaurant(latlng, name, physical_address) {
          var html = "<b>" + name + "</b> <br/>" + physical_address;
          var restaurant = new google.maps.restaurant({
            map: map,
            position: latlng
          });
          google.maps.event.addListener(restaurant, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, restaurant);
          });
          restaurants.push(restaurant);
        }

       function createOption(name, distance, num) {
          var option = document.createElement("option");
          option.value = num;
          option.innerHTML = name;
          locationSelect.appendChild(option);
       }
  function createRestaurant(latlng, name, physical_address) {
  var html = "<b>" + name + "</b> <br/>" + physical_address;
  var restaurant = new google.maps.Restaurant({
    map: map,
    position: latlng
  });
  google.maps.event.addListener(restaurant, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, restaurant);
  });
  restaurants.push(restaurant);
}

       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.responseText, request.status);
            }
          };

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

       function parseXml(str) {
          if (window.ActiveXObject) {
            var doc = new ActiveXObject('Microsoft.XMLDOM');
            doc.loadXML(str);
            return doc;
          } else if (window.DOMParser) {
            return (new DOMParser).parseFromString(str, 'text/xml');
          }
       }

       function doNothing() {}
      </script>
       <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD8YU48m7RJufra0o6ePuY2FwMX5AMZ2EU&callback=initMap"
       async defer>
   </script>
   <?php
   require("phpsqlsearch_dbinfo.php");
   // Get parameters from URL
   $center_lat = (isset( $_GET["lat"] ) ? $_GET["lat"] : 1.1026 ); 
   $center_lng =( isset( $_GET["lng"] ) ? $_GET["lng"] : -37.0132 ); 
   $radius= ( isset( $_GET["radius"] ) ? $_GET["radius"] : 25 );

  //  $center_lat = $_GET["lat"];
  //  $center_lng = $_GET["lng"];
  //  $radius = $_GET["radius"];
   // Start XML file, create parent node
   $dom = new DOMDocument("1.0");
   $node = $dom->createElement("restaurants");
   $parnode = $dom->appendChild($node);
   // Opens a connection to a mySQL server
   $connection=mysqli_connect ("127.0.0.1", $username, $password);
   if (!$connection) {
     die("Not connected : " . mysqli_error());
   }
   // Set the active mySQL database
   $db_selected = mysqli_select_db($connection,$database );
   if (!$db_selected) {
     die ("Can\'t use db : " . mysqli_error());
   }
   // Search the rows in the restaurants table
   $query = sprintf("SELECT  physical_address,opening_time,closing_time,days_of_operation,website,email,phone, lng, lat, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM restaurants HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
  mysqli_real_escape_string($connection,$center_lat),
  mysqli_real_escape_string($connection,$center_lng),
  mysqli_real_escape_string($connection,$center_lat),
  mysqli_real_escape_string($connection,$radius));
 
   $result = mysqli_query($connection,$query);
   $result = mysqli_query($connection,$query);
   if (!$result) {
     die("Invalid query: " . mysqli_error($connection));
     
   }

  echo @mysqli_fetch_assoc($result);
   while ($row = @mysqli_fetch_assoc($result)){

     $node = $dom->createElement("restaurant");
     $newnode = $parnode->appendChild($node);
     $newnode->setAttribute("name", $row['name']);
    //  $newnode->setAttribute("opening_time", $row['opening_time']);
    //  $newnode->setAttribute("closing_time", $row['closing_time']);
    //  $newnode->setAttribute("days_of_operation", $row['days_of_operation']);
    //  $newnode->setAttribute("physical_address", $row['physical_address']);
     $newnode->setAttribute("lat", $row['lat']);
     $newnode->setAttribute("lng", $row['lng']);
     $newnode->setAttribute("distance", $row['distance']);
   }

    // echo saveXML();

   echo $dom->saveXML();
   ?>
  
  
  </body>
</html>
Activity icon

Started a new Conversation Rendering Restaurants On Google Maps

i have restaurants info in my sql database having the longitude and lattitude.How do i render these restaurants on google maps

Activity icon

Started a new Conversation Restaurant Locator Using Google Maps

Who can convert this code to the MVC pattern am trying to search for nearby restaurants according to users location.am using SQL database and laravel am new to javascript.

I have the longitude and lattitude values of the restaurants in the restaurant database

where does one put this code on controllers and how does one work with XML files

Creating a Store Locator on Google Maps /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } Search location: Radius: 50 kms 30 kms 20 kms 10 kms
    <input type="button" id="searchButton" value="Search"/>
</div>
<div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
<div id="map" style="width: 100%; height: 90%"></div>
<script>
  var map;
  var markers = [];
  var infoWindow;
  var locationSelect;

    function initMap() {
      var juja = {lat:-1.1026, lng:37.0132};
      map = new google.maps.Map(document.getElementById('map'), {
        center: ,
        zoom: 11,
        mapTypeId: 'roadmap',
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
      });
      infoWindow = new google.maps.InfoWindow();

      searchButton = document.getElementById("searchButton").onclick = searchLocations;

      locationSelect = document.getElementById("locationSelect");
      locationSelect.onchange = function() {
        var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
        if (markerNum != "none"){
          google.maps.event.trigger(markers[markerNum], 'click');
        }
      };
    }

   function searchLocations() {
     var address = document.getElementById("addressInput").value;
     var geocoder = new google.maps.Geocoder();
     geocoder.geocode({address: address}, function(results, status) {
       if (status == google.maps.GeocoderStatus.OK) {
        searchLocationsNear(results[0].geometry.location);
       } else {
         alert(address + ' not found');
       }
     });
   }

   function clearLocations() {
     infoWindow.close();
     for (var i = 0; i < markers.length; i++) {
       markers[i].setMap(null);
     }
     markers.length = 0;

     locationSelect.innerHTML = "";
     var option = document.createElement("option");
     option.value = "none";
     option.innerHTML = "See all results:";
     locationSelect.appendChild(option);
   }

   function searchLocationsNear(center) {
     clearLocations();

     var radius = document.getElementById('radiusSelect').value;
     var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
     downloadUrl(searchUrl, function(data) {
       var xml = parseXml(data);
       var markerNodes = xml.documentElement.getElementsByTagName("marker");
       var bounds = new google.maps.LatLngBounds();
       for (var i = 0; i < markerNodes.length; i++) {
         var id = markerNodes[i].getAttribute("id");
         var name = markerNodes[i].getAttribute("name");
         var address = markerNodes[i].getAttribute("address");
         var distance = parseFloat(markerNodes[i].getAttribute("distance"));
         var latlng = new google.maps.LatLng(
              parseFloat(markerNodes[i].getAttribute("lat")),
              parseFloat(markerNodes[i].getAttribute("lng")));

         createOption(name, distance, i);
         createMarker(latlng, name, address);
         bounds.extend(latlng);
       }
       map.fitBounds(bounds);
       locationSelect.style.visibility = "visible";
       locationSelect.onchange = function() {
         var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
         google.maps.event.trigger(markers[markerNum], 'click');
       };
     });
   }

   function createMarker(latlng, name, address) {
      var html = "<b>" + name + "</b> <br/>" + address;
      var marker = new google.maps.Marker({
        map: map,
        position: latlng
      });
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
      markers.push(marker);
    }

   function createOption(name, distance, num) {
      var option = document.createElement("option");
      option.value = num;
      option.innerHTML = name;
      locationSelect.appendChild(option);
   }

   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.responseText, request.status);
        }
      };

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

   function parseXml(str) {
      if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
      } else if (window.DOMParser) {
        return (new DOMParser).parseFromString(str, 'text/xml');
      }
   }

   function doNothing() {}
Aug
10
3 months ago
Activity icon

Started a new Conversation Input Type For Cordinates In Laravel Form Collective

0

i have a form for storing restaurants info

    {!! Form::open(['action' => '[email protected]','method'=>'POST','enctype'=>'multipart/form-data'])!!}
    <div class="form-group">
    {{Form::label('name','Name')}}
    {{Form::text('name','',['class'=>'form-control','placeholder'=>'Insert here'])}}
    </div>
    <div class="form-group">
            {{Form::label('hours','Hours')}}
            {{Form::text('hours','',['class'=>'form-control','placeholder'=>'Insert here'])}}
            </div>
            <div class="form-group">
                    {{Form::label('contact','Contact')}}
                    {{Form::text('contact','',['class'=>'form-control','placeholder'=>'Insert here'])}}
                    </div>
            <div class="form-group">
                    {{Form::label('payment','Payment')}}
                    {{Form::text('payment','',['class'=>'form-control','placeholder'=>'Insert here'])}}
                    </div>

    <div class="form-group">
            {{Form::label('menu','Menu')}}
            {{Form::textarea('menu',null,['id'=>'menu','placeholder'=>'Insert here','name'=>'menu'])}}
    </div>
    <div class="form-group">
                    {{Form::label('description','Description')}}
                    {{Form::textarea('description',null,['id'=>'description','placeholder'=>'Insert here','name'=>'description'])}}
            </div>

    <div class="form-group">
                    {{Form::file('cover_image')}}
    </div>
    {{-- {{Form::hidden('_method','POST')}} --}}
    {{Form::submit('submit',['class'=>'btn btn-primary','type'=>'submit','id'=>'submit'])}}

    {!! Form::close() !!} 


    </div>

    </body>


    </html>

    @endsection

I need to store restaurants longitude and lattitude how do i go about that.This is the lattitude migration that i added after creating the restaurants form

public function up() { Schema::table('restaurants', function (Blueprint $table) { $table->decimal('lat', 10, 7); }); }

I need to store the restaurants cordinates so that i can query those that are nearby to the user you can help with this too

Jul
22
3 months ago
Activity icon

Started a new Conversation Query Nearby Restaurants

I need to query nearby restaurants which are 10 metres away how do i go about it?am a beginner using google maps API.Do i need to save the longitude and latitude in their restaurants table?Anyone with a tutorial on that or who will guide me will really appreciate

Jul
21
3 months ago
Activity icon

Started a new Conversation Display Reviews For A Specific Restaurant Laravel

I am trying to display reviews and ratings on a restaurant profile.

Reviews

@foreach($reviews as $review) @for ($i=1; $i @endfor {{ $review->user ? $review->user->name : 'Anonymous'}}

{{{$review->value}}}

@endforeach Error

Undefined variable: reviews (View: C:\xampp\htdocs\restaurantFinder\resources\views\restaurants\viewer.blade.php)

Reviews Controller

Show the form for creating a new resource.

  • @return \Illuminate\Http\Response */ public function create() { // }

/**

  • Store a newly created resource in storage.

  • @param \Illuminate\Http\Request $request

  • @return \Illuminate\Http\Response */ public function store(Request $request) { if (! Auth::check()) { return redirect('/index'); }

    $review=new Review; $review->user_id=auth()->user()->id; $review->restaurant_id=$request->get('restaurant_id'); $review->value=$request->input('value');

$review->rating=$request->input('rating'); 
$review->save();

}

/**

  • Display the specified resource.
  • @param int $id
  • @return \Illuminate\Http\Response */ public function show($restaurant) { // $restaurant=Restaurant::find($id); return view('restaurants.review',compact('restaurant')); }

/**

  • Show the form for editing the specified resource.
  • @param int $id
  • @return \Illuminate\Http\Response */ public function edit($id) { // }

/**

  • Update the specified resource in storage.
  • @param \Illuminate\Http\Request $request
  • @param int $id
  • @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // }

/**

  • Remove the specified resource from storage.
  • @param int $id
  • @return \Illuminate\Http\Response */ public function destroy($id) { // }
Jul
11
4 months ago
Activity icon

Replied to Error While Storing Route ID

array:2 [ "_token" => "n1QXMwrABPtJNyf10pcrlmBinAitIxMW66jCkCmU" "value" => "jkvvjvvjkvv" ]

oh its a token i guess

Activity icon

Started a new Conversation Error While Storing Route ID

Am trying to store route id of a review(it contains restaurant id) in a variable called restaurant_id in a reviews table This is the store function public function store(Request $request) { if (! Auth::check()) { return redirect('/index'); }

    $review=new Review;
    $review->user_id=auth()->user()->id;
    $review->restaurant_id=$request->route('id');
    $review->value=$request->input('value');
    $review->save();
}

This is the link on the restaurant profile that directs to the review template Add review This is the action on the form {!!Form::open(['action' => ['[email protected]'],'method'=>'POST','enctype'=>'multipart/form-data'])!!} i get the error below when submitting

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'restaurant_id' cannot be null (SQL: insert into reviews (user_id, restaurant_id, value, updated_at, created_at) values (1, ?, kkkkbkb, 2019-07-11 08:39:10, 2019-07-11 08:39:10))