RadoszSzymon

RadoszSzymon

Member Since 1 Year Ago

Experience Points 2,530
Experience Level 1

2,470 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 21
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.

19 Feb
1 year ago

RadoszSzymon left a reply on Ajax Request To Controller

I made some changes, but still I have some questions. There is my code:

pages/index.blade.php

@extends('layouts.app')

@section('content')
  <div class="row searchBar">
        <div class="col-sm-4 col-sm-offset-4 col-xs-8 col-xs-offset-2">
            <!-- step numbers -->
            <div class="stepButtons">
              <div class="first">
                <p>1</p>
              </div>

              <div class="second">
                <p>2</p>
              </div>

              <div class="third">
                <p>3</p>
              </div>
            </div>

            <!-- search by location -->
            <div class="searchForm">
              <form class="form-horizontal" method="post" action="/search">
                <div class="form-group">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="location" name="location" value="" placeholder="find drop off point">
                    </div>
                </div>
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
            </div>

            <!-- search by current position -->
           <div class="currentPoints">
              <form class="form-horizontal" >
                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLat" name="pointLat" value="" placeholder="lat">
                    </div>
                </div>

                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLng" name="pointLng" value="" placeholder="lng">
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-lg-12">
                         <button type="submit" class="btn btn-primary" id="morePoints">SEARCH THIS AREA</button>
                    </div>
                </div>

                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
          </div>


        </div>
  </div>

  <div id="mapGoogle">
       {!! Mapper::render() !!}
  </div>

  <div id="infoPanel"></div>
@endsection



<script>
  function markerClick(){
    $('#infoPanel').css('display', 'block');
  }
</script>

<script>
    function checkPosition(map) {

    var searchBox = new google.maps.places.SearchBox(document.getElementById('location'));

    /*google.maps.event.addListener(searchBox, 'places_changed', function () {
      var places = searchBox.getPlaces();
      var bounds = new google.maps.LatLngBounds();
      var i, place;
      for (i = 0; place = places[i]; i++) {
          bounds.extend(place.geometry.location);
          marker_0.setPosition(place.geometry.location);
      }
      map.fitBounds(bounds);
      map.setZoom(15);
    });*/

        document.onclick = function(){
            var ctr = map.getCenter();

            var lt =ctr.lat();
            var lng=ctr.lng();

            console.log(lt);
            console.log(lng);

            $('#morePoints').css('display', 'block');   

      $(function() {
        $("#morePoints").click( function()
          {
            $('#pointLat').val(lt);
            $('#pointLng').val(lng);
    
            $.ajax({
              type: "GET",
              url: 'Myapi' +  lt + '&lng=' + lng + '&distance=3',
             
              success: function(data) {
                      marker = new google.maps.Marker({
                      position: new google.maps.LatLng(data.lat, data.long),
                      map: map,
                      title: 'test'
                  });
              }
            });
          }
        );
      });

        }
    }
</script>

PagesController.php

<?php

namespace App\Http\Controllers;

use Request;
use Mapper;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Input;

class PagesController extends Controller
{
  public function index(){

    //take lgt and lat from point- london
    $latitude = 51.500407513572796;
    $longitude = -0.129061164107939;

    //init map
    Mapper::map(
        $latitude, 
        $longitude,
        [
            'zoom' => 16, 
            'center' => true, 
            'marker' => false, 
            'scrollwheel' => true,
            'draggable' => false,
            'disableDefaultUI' => true,
            'eventBeforeLoad' => 'checkPosition(map);',
        ]
    );

    //guzzle http response to take points from api
    $client = new \GuzzleHttp\Client([
        'base_uri' => 'http://localhost:8000',
        'defaults' => [
            'exceptions' => false
        ]
    ]);
    //return nearest points from api
    $response = $client->get('MyApi?lat=' . $latitude . '&lng=' . $longitude .'&distance=3')->getBody();

    //convert response to json format
    $json = json_decode($response, true);

    //get only 'results' from json
    $results = $json['results'];

    //get amount of points from results
    $amount = count($json['results']);

    //fore every point create marker with latitude and longitude
    for($i = 0; $i < $amount; $i++){

        //get point address data
        $addressName = $results[$i]['point_data']['address']['name'];
        $addressAddress = $results[$i]['point_data']['address']['address'];
        $addressCity = $results[$i]['point_data']['address']['city'];
        $addressPostCode = $results[$i]['point_data']['address']['postcode'];

        //create marker width lng and lat, add poind address data to #infoPanel div after click point
        Mapper::marker(
            $results[$i]['lat'], 
            $results[$i]['lng'], 
            [
                'draggable' => true, 
                'eventClick' => 'document.getElementById("infoPanel").innerHTML = "' . '<p>' . $addressName .  '<br>' .
                                                                                                $addressAddress . '<br>' .  
                                                                                                $addressCity . '<br>' .  
                                                                                                $addressPostCode . '</p>' . '"; markerClick(); '
            ]
        );
    }  
    
    //return $response to pages/index view
    return view('pages.index')->with('response', $response);
  }


  public function store(){

    if(Input::has('location')){
        //get input location
        $input = Input::get('location');

        $loc = Mapper::location($input);

        //take lgt and lat from point
        $latitude = $loc->getLatitude();
        $longitude = $loc->getLongitude();

        //guzzle http response to take points from api
        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://localhost:8000',
            'defaults' => [
                'exceptions' => false
            ]
        ]);
        //return nearest points from api
        $response = $client->get('MyApi?lat=' . $latitude . '&lng=' . $longitude .'&distance=3')->getBody();

        //convert response to json format
        $json = json_decode($response, true);

        //test data
        //$test = var_dump(json_decode($response, true));

        //get only 'results' from json
        $results = $json['results'];

        //get amount of points from results
        $amount = count($json['results']);

        return response()->json([ 'location' => $results ]);
    } elseif(Input::has('pointLat')&&Input::has('pointLng')){

        $latitude = Input::get('pointLat');
        $longitude = Input::get('pointLng');


        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://localhost:8000',
            'defaults' => [
                'exceptions' => false
            ]
        ]);

        $response = $client->get('MyApi?lat=' . $latitude . '&lng=' . $longitude .'&distance=3')->getBody();
       
        //convert response to json format
        $json = json_decode($response, true);

        //test data
        //$test = var_dump(json_decode($response, true));

        //get only 'results' from json
        $results = $json['results'];

        //get amount of points from results
        $amount = count($json['results']);

        return response()->json([ 'location' => $results ]);

    }

    return view('pages.index');

    }

}

Now I removed action in my 'currentPoints' form and when the user click button I make ajax request to get point from api and try to make markers, but page reload and url looks like 'http://127.0.0.1:8000/?pointLat=51.503859648407776&pointLng=-0.20387134652673922&_token=2InctW0ik7Evh3Xqeo9E8i9tVoz4MGtp9oCETvd0'. Now the index() is call and map load points like at the beginning.

My PagesController/store return json data as well, but should I call this method or I can download data by ajax request and update marker. I don't have bright idea how to make that efficient without reload website. I really appreciate your help.

16 Feb
1 year ago

RadoszSzymon started a new conversation Ajax Request To Controller

Hi guys. I created the app and I take points coordinates for my google maps(created by Googlmapper api for laravel) from external api.

I created jquery event when the user makes something in the map(grab, move, etc.) I display a button "search this area" and I add value to hidden inputs and send data to PointsController store() method. I have also a text field in my pages where a user write location and that location is send to PagesController store() method. It works fine, but now I want to update map without reload on my root url. I tried make some ajax request, but I don't have any good idea how to make that properly. Maybe I need some parameters with cordinates in my routes/web for [email protected] and change that by ajax? Do you have an idea how to make that process without reloading(display map on home page focused in London at the start and then after send data by search form or by another form when user click button 'search this area' make request which take points data in json and update the map)?

I attach my code. Thanks for any advice.

PagesController.php

<?php

namespace App\Http\Controllers;

use Request;
use Mapper;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Input;

class PagesController extends Controller
{
  public function index(){
    //take lgt and lat from point- london
    $latitude = 51.500407513572796;
    $longitude = -0.129061164107939;

    //init map
    Mapper::map(
        $latitude, 
        $longitude,
        [
            'zoom' => 16, 
            'center' => true, 
            'marker' => false, 
            'scrollwheel' => true,
            'draggable' => false,
            'disableDefaultUI' => true,
            'eventBeforeLoad' => 'checkPosition(map);',
        ]
    );

    //guzzle http response to take points from api
    $client = new \GuzzleHttp\Client([
        'base_uri' => 'http://localhost:8000',
        'defaults' => [
            'exceptions' => false
        ]
    ]);
    //return nearest points from api
    $response = $client->get('MYAPI?lat=' . $latitude . '&lng=' . $longitude .'&distance=3')->getBody();

    //convert response to json format
    $json = json_decode($response, true);

    //get only 'results' from json
    $results = $json['results'];

    //get amount of points from results
    $amount = count($json['results']);

    //fore every point create marker with latitude and longitude
    for($i = 0; $i < $amount; $i++){

        //get point address data
        $addressName = $results[$i]['point_data']['address']['name'];
        $addressAddress = $results[$i]['point_data']['address']['address'];
        $addressCity = $results[$i]['point_data']['address']['city'];
        $addressPostCode = $results[$i]['point_data']['address']['postcode'];

        //create marker width lng and lat, add poind address data to #infoPanel div after click point
        Mapper::marker(
            $results[$i]['lat'], 
            $results[$i]['lng'], 
            [
                'draggable' => true, 
                'eventClick' => 'document.getElementById("infoPanel").innerHTML = "' . '<p>' . $addressName .  '<br>' .
                                                                                                $addressAddress . '<br>' .  
                                                                                                $addressCity . '<br>' .  
                                                                                                $addressPostCode . '</p>' . '"; markerClick(); '
            ]
        );
    }  

    //return $response to pages/index view
    return view('pages.index')->with('response', $response);
  }


  public function store(){
    //get input location
    $input = Input::get('location');

    //center map in location point
    Mapper::location($input)->map(
        [
            'zoom' => 16, 
            'center' => true, 
            'marker' => false, 
            'scrollwheel' => true,
            'disableDefaultUI' => true,
            'gestureHandling' => 'greedy',
            'eventBeforeLoad' => 'checkPosition(map);',
        ]
    );

    //get location info
    $loc = Mapper::location($input);

    //take lgt and lat from point
    $latitude = $loc->getLatitude();
    $longitude = $loc->getLongitude();

    //guzzle http response to take points from api
    $client = new \GuzzleHttp\Client([
        'base_uri' => 'http://localhost:8000',
        'defaults' => [
            'exceptions' => false
        ]
    ]);
    //return nearest points from api
    $response = $client->get('MYAPI?lat=' . $latitude . '&lng=' . $longitude .'&distance=3')->getBody();
    
    //convert response to json format
    $json = json_decode($response, true);

    //test data
    //$test = var_dump(json_decode($response, true));

    //get only 'results' from json
    $results = $json['results'];

    //get amount of points from results
    $amount = count($json['results']);

    //fore every point create marker with latitude and longitude
    for($i = 0; $i < $amount; $i++){

        //get point address data
        $addressName = $results[$i]['point_data']['address']['name'];
        $addressAddress = $results[$i]['point_data']['address']['address'];
        $addressCity = $results[$i]['point_data']['address']['city'];
        $addressPostCode = $results[$i]['point_data']['address']['postcode'];

        //create marker width lng and lat, add poind address data to #infoPanel div after click point
        Mapper::marker(
            $results[$i]['lat'], 
            $results[$i]['lng'], 
            [
                'draggable' => true, 
                'eventClick' => 'document.getElementById("infoPanel").innerHTML = "' . '<p>' . $addressName .  '<br>' .
                                                                                                $addressAddress . '<br>' .  
                                                                                                $addressCity . '<br>' .  
                                                                                                $addressPostCode . '</p>' . '"; markerClick(); '
            ]
        );
    }  
      
    //send variables to pages/search to use it
    return view('pages.search')->with(['latitude' => $latitude, 'longitude' => $longitude]);
    }


    //list of coupons
    public function couponsList(){
        //guzzle http response to take points from api
        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://localhost:8000',
            'defaults' => [
                'exceptions' => false
            ]
        ]);

        $response = $client->get('https://app.regain-app.com/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=status&searchCriteria[filter_groups][0][filters][0][value]=1')->getBody();
        
        //convert response to json format
        $json = json_decode($response, true);

        $coupons = $json['items'];

        return view('pages.couponsList')->with('coupons', $coupons);
    }
}

PointsController.php

<?php

namespace App\Http\Controllers;

use Request;
use Mapper;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Input;

class PointsController extends Controller
{
    public function index(){
        $latitude = 51.500407513572796;
        $longitude = -0.129061164107939;
    
        Mapper::map(
            $latitude, 
            $longitude,
            [
                'zoom' => 14, 
                'center' => true, 
                'marker' => false, 
                'scrollwheel' => true,
                'draggable' => false,
                'disableDefaultUI' => true,
                'eventBeforeLoad' => 'checkPosition(map);',
            ]
        );
    
        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://localhost:8000',
            'defaults' => [
                'exceptions' => false
            ]
        ]);
        
        $response = $client->get('MYAPI?lat=' . $latitude . '&lng=' . $longitude .'&distance=3')->getBody();
        $json = json_decode($response, true);
        $results = $json['results'];
        $amount = count($json['results']);

        for($i = 0; $i < $amount; $i++){

            $addressName = $results[$i]['point_data']['address']['name'];
            $addressAddress = $results[$i]['point_data']['address']['address'];
            $addressCity = $results[$i]['point_data']['address']['city'];
            $addressPostCode = $results[$i]['point_data']['address']['postcode'];
    
            Mapper::marker(
                $results[$i]['lat'], 
                $results[$i]['lng'], 
                [
                    'draggable' => true, 
                    'eventClick' => 'document.getElementById("infoPanel").innerHTML = "' . '<p>' . $addressName .  '<br>' .
                                                                                                    $addressAddress . '<br>' .  
                                                                                                    $addressCity . '<br>' .  
                                                                                                    $addressPostCode . '</p>' . '"; markerClick(); '
                ]
            );
        }  
    
        return view('pages.index');
      }


    public function store(){
        $latitude = Input::get('pointLat');
        $longitude = Input::get('pointLng');
    
        Mapper::map(
            $latitude, 
            $longitude,
            [
                'zoom' => 14, 
                'center' => true, 
                'marker' => false, 
                'scrollwheel' => true,
                'draggable' => false,
                'disableDefaultUI' => true,
                'eventBeforeLoad' => 'checkPosition(map);',
            ]
        );

        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://localhost:8000',
            'defaults' => [
                'exceptions' => false
            ]
        ]);

        $response = $client->get('MYAPI?lat=' . $latitude . '&lng=' . $longitude .'&distance=3')->getBody();
        $json = json_decode($response, true);
        $results = $json['results'];
        $amount = count($json['results']);

        for($i = 0; $i < $amount; $i++){
            $addressName = $results[$i]['point_data']['address']['name'];
            $addressAddress = $results[$i]['point_data']['address']['address'];
            $addressCity = $results[$i]['point_data']['address']['city'];
            $addressPostCode = $results[$i]['point_data']['address']['postcode'];

            Mapper::marker(
                $results[$i]['lat'], 
                $results[$i]['lng'], 
                [
                    'draggable' => true, 
                    'eventClick' => 'document.getElementById("infoPanel").innerHTML = "' . '<p>' . $addressName .  '<br>' .
                                                                                                    $addressAddress . '<br>' .  
                                                                                                    $addressCity . '<br>' .  
                                                                                                    $addressPostCode . '</p>' . '"; markerClick(); '
                ]
            );
        }  
          
        return view('points.index');
        }
}

pages/index.blade.php

@extends('layouts.app')

@section('content')
  <div class="row searchBar">
        <div class="col-sm-4 col-sm-offset-4 col-xs-8 col-xs-offset-2">
            <!-- step numbers -->
            <div class="stepButtons">
              <div class="first">
                <p>1</p>
              </div>

              <div class="second">
                <p>2</p>
              </div>

              <div class="third">
                <p>3</p>
              </div>
            </div>

            <div class="searchForm">
              <form class="form-horizontal" method="post" action="/search">
                <div class="form-group">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="location" name="location" value="" placeholder="find drop off point">
                    </div>
                </div>
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
            </div>

           <div class="currentPoints">
              <form class="form-horizontal" method="post" action="/points">
                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLat" name="pointLat" value="" placeholder="lat">
                    </div>
                </div>

                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLng" name="pointLng" value="" placeholder="lng">
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-lg-12">
                         <button type="submit" class="btn btn-primary" id="morePoints">SEARCH THIS AREA</button>
                    </div>
                </div>

                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
          </div>


        </div>
  </div>
  <div id="mapGoogle">
       {!! Mapper::render() !!}
  </div>

  <div id="infoPanel"></div>
@endsection

<script>
  function markerClick(){
    $('#infoPanel').css('display', 'block');
  }
</script>

<script>
    function checkPosition(map) {

    var searchBox = new google.maps.places.SearchBox(document.getElementById('location'));

    google.maps.event.addListener(searchBox, 'places_changed', function () {
      var places = searchBox.getPlaces();
      var bounds = new google.maps.LatLngBounds();
      var i, place;
      for (i = 0; place = places[i]; i++) {
          bounds.extend(place.geometry.location);
          marker_0.setPosition(place.geometry.location);
      }
      map.fitBounds(bounds);
      map.setZoom(15);
    });

        document.onclick = function(){
            var ctr = map.getCenter();

            var lt =ctr.lat();
            var lng=ctr.lng();

            console.log(lt);
            console.log(lng);

            $('#morePoints').css('display', 'block');   

      $(function() {
        $("#morePoints").click( function()
          {
            $('#pointLat').val(lt);
            $('#pointLng').val(lng);
          }
        );
      });

        }
    }
</script>

pages/search.blade.php

@extends('layouts.app')

@section('content')
  <div class="row searchBar">
        <div class="col-sm-4 col-sm-offset-4 col-xs-8 col-xs-offset-2">
            <!-- step numbers -->
            <div class="stepButtons">
              <div class="first">
                <p>1</p>
              </div>

              <div class="second">
                <p>2</p>
              </div>

              <div class="third">
                <p>3</p>
              </div>
            </div>

            <div class="searchForm">
              <form class="form-horizontal" method="post" action="/search">
                <div class="form-group">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="location" name="location" value="" placeholder="find drop off point">
                    </div>
                </div>
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
            </div>

           <div class="currentPoints">
              <form class="form-horizontal" method="post" action="/points">
                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLat" name="pointLat" value="" placeholder="lat">
                    </div>
                </div>

                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLng" name="pointLng" value="" placeholder="lng">
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-lg-12">
                         <button type="submit" class="btn btn-primary" id="morePoints">SEARCH THIS AREA</button>
                    </div>
                </div>

                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
          </div>


        </div>
  </div>
  <div id="mapGoogle">
       {!! Mapper::render() !!}
  </div>

  <div id="infoPanel"></div>
@endsection

<script>
  function markerClick(){
    $('#infoPanel').css('display', 'block');
  }
</script>

<script>
    function checkPosition(map) {

    var searchBox = new google.maps.places.SearchBox(document.getElementById('location'));

    google.maps.event.addListener(searchBox, 'places_changed', function () {
      var places = searchBox.getPlaces();
      var bounds = new google.maps.LatLngBounds();
      var i, place;
      for (i = 0; place = places[i]; i++) {
          bounds.extend(place.geometry.location);
          marker_0.setPosition(place.geometry.location);
      }
      map.fitBounds(bounds);
      map.setZoom(15);
    });

        document.onclick = function(){
            var ctr = map.getCenter();

            var lt =ctr.lat();
            var lng=ctr.lng();

            console.log(lt);
            console.log(lng);

            $('#morePoints').css('display', 'block');   

      $(function() {
        $("#morePoints").click( function()
          {
            $('#pointLat').val(lt);
            $('#pointLng').val(lng);
          }
        );
      });

        }
    }
</script>

points/index.blade.php

@extends('layouts.app')

@section('content')
  <div class="row searchBar">
        <div class="col-sm-4 col-sm-offset-4 col-xs-8 col-xs-offset-2">
            <!-- step numbers -->
            <div class="stepButtons">
              <div class="first">
                <p>1</p>
              </div>

              <div class="second">
                <p>2</p>
              </div>

              <div class="third">
                <p>3</p>
              </div>
            </div>

            <div class="searchForm">
              <form class="form-horizontal" method="post" action="/search">
                <div class="form-group">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="location" name="location" value="" placeholder="find drop off point">
                    </div>
                </div>
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
            </div>

           <div class="currentPoints">
              <form class="form-horizontal" method="post" action="/points">
                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLat" name="pointLat" value="" placeholder="lat">
                    </div>
                </div>

                <div class="form-group" style="display: none;">
                    <div class="col-lg-12">
                        <input type="text" class="form-control" id="pointLng" name="pointLng" value="" placeholder="lng">
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-lg-12">
                         <button type="submit" class="btn btn-primary" id="morePoints">SEARCH THIS AREA</button>
                    </div>
                </div>

                <input type="hidden" name="_token" value="{{ csrf_token() }}">
              </form>
          </div>


        </div>
  </div>
  <div id="mapGoogle">
       {!! Mapper::render() !!}
  </div>

  <div id="infoPanel"></div>
@endsection

<script>
  function markerClick(){
    $('#infoPanel').css('display', 'block');
  }
</script>

<script>
    function checkPosition(map) {

    var searchBox = new google.maps.places.SearchBox(document.getElementById('location'));

    google.maps.event.addListener(searchBox, 'places_changed', function () {
      var places = searchBox.getPlaces();
      var bounds = new google.maps.LatLngBounds();
      var i, place;
      for (i = 0; place = places[i]; i++) {
          bounds.extend(place.geometry.location);
          marker_0.setPosition(place.geometry.location);
      }
      map.fitBounds(bounds);
      map.setZoom(15);
    });

        document.onclick = function(){
            var ctr = map.getCenter();

            var lt =ctr.lat();
            var lng=ctr.lng();

            console.log(lt);
            console.log(lng);

            $('#morePoints').css('display', 'block');   

      $(function() {
        $("#morePoints").click( function()
          {
            $('#pointLat').val(lt);
            $('#pointLng').val(lng);
          }
        );
      });

        }
    }
</script>

routes/web.php

Route::get('/', '[email protected]');
Route::resource('search','PagesController');

Route::resource('points', 'PointsController');

//list of available coupons
Route::get('/couponsList', '[email protected]');

//user registration and page after register
Route::get('/registration', '[email protected]');
Route::resource('registerSubmit','RegistrationController');

//user login and page after login
Route::get('/login', '[email protected]');
Route::resource('loginSubmit','RegistrationController');

26 Jan
1 year ago

RadoszSzymon left a reply on Can't Take Data For Current User

Habit::all() return all records from db, but code from your answer doesn't return any record.

RadoszSzymon left a reply on Can't Take Data For Current User

Yes, I have table user_id and it works perfect. There is a screenshot. I don't know why it doesn't work. https://imgur.com/a/4nGki

RadoszSzymon started a new conversation Can't Take Data For Current User

Hi. I have some problem with my app. I want to display data belongs to current user, but it's still doesn't work. In my DB I have tables 'habits' and 'users' and now I want to display all data at index view. When I try with $single = Habit::all(); It works fine and return all data from db. In the other hand I can't return data belongs to user.

HabitsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Habit;
use App\User;
use DB;
use Auth;
use App\Quotation;

class HabitsController extends Controller
{
     /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       //store in $habits all posts of current user 
       // $habits = DB::table('habits')->where('user_id', auth()->id())->get();
        $habits = Habit::where('user_id', auth()->id())->get();
        return view('habits.index')->with('habits', $habits);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('habits.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name'=>'required',
            'description'=>'required',
            'difficulty'=>'required'
        ]);

        $habit = new Habit;
        $habit->name = $request->input('name');
        $habit->description = $request->input('description');
        $habit->difficulty = $request->input('difficulty');
        $habit->NumberOfCompleted = 0;
        $habit->user_id = auth()->user()->id;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $single = Habit::find($id);

        return view('habits.show')->with('single', $single);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $single = Habit::find($id);
        return view('habits.edit')->with('single', $single);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name'=>'required',
            'description'=>'required',
            'difficulty'=>'required'
        ]);

        $habit = Habit::find($id);
        $habit->name = $request->input('name');
        $habit->description = $request->input('description');
        $habit->difficulty = $request->input('difficulty');
        $habit->NumberOfCompleted = 0;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $single = Habit::find($id);
        $single->delete();

        return redirect('/habits')->with('success', 'Habit deleted');
    }

    /*method to add points to user */
    public function addPoint($id){
        /*find logged user and increment column points*/
        $user = Auth::user()->increment('points');

        $task = DB::table('habits')->where('id', '=', $id)->increment('NumberOfCompleted');

        return redirect('/habits')->with('success', 'Habit created', 'id', $id);
    }

}

Habit.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Habit extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }
}

User.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',
    ];

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

Can you give me some advice?

22 Jan
1 year ago
21 Jan
1 year ago

RadoszSzymon left a reply on Set Default Value For User

I want to display values from table 'habits' inside parent table 'happ'

RadoszSzymon left a reply on Set Default Value For User

Ok now I can register, thank you so much.

Now I have another problem. I create a table 'happ' in phpmyadmin and declare that in .env file. Now my users can be saved and they can save some data in form. In phpmyadmin I see everything work fine, but I have some problem with read data from db and display in view.

db schema:

happ: -habits -migrations -password_resets -users

HabitsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Habit;
use App\User;
use DB;
use Auth;
use App\Quotation;

class HabitsController extends Controller
{
     /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       //store in $habits all posts of current user 
        $habits = DB::table('habits')->where('user_id', auth()->id())->get();

        return view('habits.index')->with('habits', $habits);
    }

When i use DB::table('habits') the app know that I mean happ->'habits' table?

RadoszSzymon started a new conversation Set Default Value For User

Hi guys. I have some problems with registration to my app. I db for users I have additional field 'points' (I want to set that field 'points' to value 0 at the beginning) and when I try to register new user it gives my an error.

SQLSTATE[HY000]: General error: 1364 Field 'points' doesn't have a default value (SQL: insert into `users` (`name`, `email`, `password`, `updated_at`, `created_at`)

there is my registration controller.


namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}
06 Jan
1 year ago

RadoszSzymon left a reply on Increment Value By Button Click

Ok I make that. Thanks for all.

04 Jan
1 year ago

RadoszSzymon left a reply on Increment Value By Button Click

Can you give me quick note how to make that in controller instead of routes?

RadoszSzymon left a reply on Increment Value By Button Click

Ok I solved that. I do that in routes/web.php ommiting controller.

routes/web.php

Route::get('/', '[email protected]');
Route::get('/about', '[email protected]');
Route::get('habits/add-point/{user}', function($id){
    $user = DB::table('users')->where('id', '=', $id)->increment('points');

    return redirect('/habits')->with('success', 'Habit created');
});
Route::resource('habits', 'HabitsController');
Auth::routes();
Route::get('/dashboard', '[email protected]');
?>

habits/show.php

@extends('layouts/app')

@section('content')
<div class="row single">
    <div class="col-sm-8 col-sm-offset-2 showSingleHabit">
        <h2>{{$single->name}}</h2>
        <p>{{$single->description}}</p>
        <p>{{$single->difficulty}}</p>
        <p>{{$single->NumberOfCompleted}}</p>
        <a href="/habits/{{$single->id}}/edit" class="btn btn-default">Edit</a>
        
        {!!Form::open(['action' => ['[email protected]', $single->id], 'method' => 'POST'])!!}
            {{Form::hidden('_method', 'DELETE')}}
            {{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
        {!!Form::close()!!}

        <a href="http://127.0.0.1:8000/habits/add-point/{{Auth::id()}}">ADD </a>

    </div>
</div>
@endsection

And now after click 'ADD' button app increment column 'points' for current user. Am I think right or its better way to do that?

RadoszSzymon left a reply on Increment Value By Button Click

I don't understand your idea. Can you give me some code example?

03 Jan
1 year ago

RadoszSzymon left a reply on Increment Value By Button Click

There is an error: Trying to get property of non-object (View: C:\xampp\htdocs\happ\resources\views\habits\show.blade.php)

RadoszSzymon started a new conversation Increment Value By Button Click

Hi. I have an app to store habits and I want to add mechanism to increment points for users when user click button.

The user has db field 'points'.

There is my current code(It doesn't work).

HabitsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Habit;
use App\User;
use DB;
use App\Quotation;

class HabitsController extends Controller
{
     /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       //store in $habits all posts of current user 
        $habits = DB::table('habits')->where('user_id', auth()->id())->get();

        return view('habits.index')->with('habits', $habits);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('habits.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name'=>'required',
            'description'=>'required',
            'difficulty'=>'required'
        ]);

        $habit = new Habit;
        $habit->name = $request->input('name');
        $habit->description = $request->input('description');
        $habit->difficulty = $request->input('difficulty');
        $habit->NumberOfCompleted = 0;
        $habit->user_id = auth()->user()->id;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $single = Habit::find($id);

        return view('habits.show')->with('single', $single);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $single = Habit::find($id);
        return view('habits.edit')->with('single', $single);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name'=>'required',
            'description'=>'required',
            'difficulty'=>'required'
        ]);

        $habit = Habit::find($id);
        $habit->name = $request->input('name');
        $habit->description = $request->input('description');
        $habit->difficulty = $request->input('difficulty');
        $habit->NumberOfCompleted = 0;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $single = Habit::find($id);
        $single->delete();

        return redirect('/habits')->with('success', 'Habit deleted');
    }

    public function addPoint($id)
    {
        $habit = User::find($id);
        $habit->points+= 1;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }
}

habits/show.blade.php

@extends('layouts/app')

@section('content')
<div class="row single">
    <div class="col-sm-8 col-sm-offset-2 showSingleHabit">
        <h2>{{$single->name}}</h2>
        <p>{{$single->description}}</p>
        <p>{{$single->difficulty}}</p>
        <p>{{$single->NumberOfCompleted}}</p>
        <a href="/habits/{{$single->id}}/edit" class="btn btn-default">Edit</a>
        
        {!!Form::open(['action' => ['[email protected]', $single->id], 'method' => 'POST'])!!}
            {{Form::hidden('_method', 'DELETE')}}
            {{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
        {!!Form::close()!!}

        <a href="{{action('[email protected]')}}">Add Point</a>
    </div>
</div>
@endsection

routes/web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', '[email protected]');
Route::get('/about', '[email protected]');
Route::put('habits/add-point', '[email protected]');
Route::resource('habits', 'HabitsController');
Auth::routes();
Route::get('/dashboard', '[email protected]');
?>

What is the most efficient way to make that happen? I will be grateful for any help.

RadoszSzymon left a reply on Function Not Defined

I change an order in my routes, but error still happen.

routes/web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', '[email protected]');
Route::get('/about', '[email protected]');
Route::put('habits/add-point', '[email protected]');
Route::resource('habits', 'HabitsController');
Auth::routes();
Route::get('/dashboard', '[email protected]');
?>

Error message: Trying to get property of non-object (View: C:\xampp\htdocs\happ\resources\views\habits\show.blade.php)

Maybe I wrong think about that problem. Is there any easy way to change db value by clicking the button?

02 Jan
1 year ago

RadoszSzymon left a reply on Function Not Defined

In which place I have to change that?

RadoszSzymon left a reply on Function Not Defined

It's still the same error.

RadoszSzymon left a reply on Function Not Defined

show.blade.php

@extends('layouts/app')

@section('content')
<div class="row single">
    <div class="col-sm-8 col-sm-offset-2 showSingleHabit">
        <h2>{{$single->name}}</h2>
        <p>{{$single->description}}</p>
        <p>{{$single->difficulty}}</p>
        <p>{{$single->NumberOfCompleted}}</p>
        <a href="/habits/{{$single->id}}/edit" class="btn btn-default">Edit</a>
        
        {!!Form::open(['action' => ['[email protected]', $single->id], 'method' => 'POST'])!!}
            {{Form::hidden('_method', 'DELETE')}}
            {{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
        {!!Form::close()!!}

         {!!Form::open(['action' => ['[email protected]', $single->id], 'method' => 'PUT'])!!}
            {{Form::hidden('_method', 'PUT')}}
            {{Form::submit('Add point', ['class' => 'btn btn-primary'])}}
        {!!Form::close()!!}
    </div>
</div>
@endsection

HabitsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Habit;
use App\User;
use DB;
use App\Quotation;

class HabitsController extends Controller
{
     /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       //store in $habits all posts of current user 
        $habits = DB::table('habits')->where('user_id', auth()->id())->get();

        return view('habits.index')->with('habits', $habits);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('habits.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name'=>'required',
            'description'=>'required',
            'difficulty'=>'required'
        ]);

        $habit = new Habit;
        $habit->name = $request->input('name');
        $habit->description = $request->input('description');
        $habit->difficulty = $request->input('difficulty');
        $habit->NumberOfCompleted = 0;
        $habit->user_id = auth()->user()->id;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $single = Habit::find($id);

        return view('habits.show')->with('single', $single);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $single = Habit::find($id);
        return view('habits.edit')->with('single', $single);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name'=>'required',
            'description'=>'required',
            'difficulty'=>'required'
        ]);

        $habit = Habit::find($id);
        $habit->name = $request->input('name');
        $habit->description = $request->input('description');
        $habit->difficulty = $request->input('difficulty');
        $habit->NumberOfCompleted = 0;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $single = Habit::find($id);
        $single->delete();

        return redirect('/habits')->with('success', 'Habit deleted');
    }

    public function addPoint($id)
    {
        $habit = User::find($id);
        $habit->points += 1;
        $habit->save();

        return redirect('/habits')->with('success', 'Habit created');
    }
}

routes/web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', '[email protected]');
Route::get('/about', '[email protected]');

Route::resource('habits', 'HabitsController');
Auth::routes();

Route::get('/dashboard', '[email protected]');

Route::put('habits/add-point', '[email protected] '); 

?>

RadoszSzymon left a reply on Function Not Defined

I think there is some conflicts in controller and view, but I can find proper solution.

I have in view ['[email protected]', $single->id], but in controller I have addPoint method without $single variable. In the other hand I use $single in show method. I don't have idea how to fix that.

RadoszSzymon left a reply on Function Not Defined

addPoint method.

RadoszSzymon left a reply on Function Not Defined

HabitsController.php

RadoszSzymon started a new conversation Function Not Defined

I have problem: I build first app and I have 2 tables in my db: habits and users. The User has a field called points and after click a button 'Add point' I want to increment that value. I added a method in HabitsController called addPoints and button in a view, but I get an error message: Action App\Http\Controllers\[email protected] not defined. (View: C:\xampp\htdocs\happ\resources\views\habits\show.blade.php). There is my code.

HabitsController.php