尝试从laravel 5中的数据库中检索所有用户名

时间:2015-10-06 10:44:51

标签: php laravel-5

我正在学习laravel 5.我想从数据库中列出我页面上的所有用户名。

这是我正在使用的控制器:

import UIKit
import MapKit
import CoreLocation
import Parse

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UIActionSheetDelegate {


    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var segmentedControl: UISegmentedControl!

    let locationManager = CLLocationManager()
    let kDefaultKmForUserOnMap = 50.0                   //default value

    var limitNumberForQueryResults = 10

    var closeUsersArray:[String] = []                   //MARK: Test

    let defaults = NSUserDefaults.standardUserDefaults()
    var withinKms : Double!



    override func viewDidLoad()
    {
        super.viewDidLoad()


        //MARK: checks if the variable is nil, if yes, attributes a value
        if defaults.doubleForKey("withinKms") <= 0 {
            defaults.setDouble(kDefaultKmForUserOnMap, forKey: "withinKms")
            defaults.synchronize()
            withinKms = defaults.doubleForKey("withinKms")
            println("MapViewController - viewDidLoad - var kKmRadiusForUsersOnMap was never set before, so now is set to  \(withinKms) ")
        } else {
            withinKms = defaults.doubleForKey("withinKms")
            println("MapViewController - viewDidLoad - else occurred and var test is \(withinKms)")
        }



        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()

        self.mapView.showsUserLocation = true

    }


    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

    }



    override func viewDidAppear(animated: Bool)
    {
        super.viewDidAppear(animated)

        self.segmentedControl.selectedSegmentIndex = 0

        withinKms = self.defaults.doubleForKey("withinKms")
        println("MapViewController - viewDidAppear - radius shown on map is * \(withinKms) * ")

    }





    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "fromMapToNewChats" {

            //MARK: Hint - this is the standard way to pass data to a NOT embedded VC

            var nextVC : NewChatsFromHomeVC = segue.destinationViewController as! NewChatsFromHomeVC
            nextVC.calledFromVC = "MapViewController"
            nextVC.receivedReceiver = "Specific User"

//            //        nextVC.filterToParse = self.channleKeywordReceived

        }

    }



    //************************************************

    //MARK: send message by touching an annotation

    func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {

        println("anotation pressed: \(view.annotation.title)")

        self.performSegueWithIdentifier("fromMapToNewChats", sender: self)

    }

    //************************************************




    // MARK: - Location Delegate Methods

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
        let point = PFGeoPoint(latitude:manager.location.coordinate.latitude, longitude:manager.location.coordinate.longitude)
        let location = locations.last as! CLLocation

        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))

        self.mapView.setRegion(region, animated: true)

        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in

            if (error != nil)
            {
                println("Error: " + error.localizedDescription)
                return
            }

            if placemarks.count > 0
            {
                let pm = placemarks[0] as! CLPlacemark
                self.displayLocationInfo(pm, point: point)
                println("evaluates 3")
            }
            else
            {
                println("Error with the data.")
            }
        })
    }





    func displayLocationInfo(placemark: CLPlacemark, point: PFGeoPoint)
    {
        self.locationManager.stopUpdatingLocation()

        self.createAnnotations(point, address: "\(placemark.locality) \(placemark.administrativeArea) \(placemark.postalCode) \(placemark.country)")
    }





    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
    {
        println("Error: " + error.localizedDescription)
    }



//    timelineMessageDataArray.removeAll(keepCapacity: true)          //erase previus contents
//    println("timelineData cleared")


    // MARK: - Create Annotation

    func createAnnotations(point: PFGeoPoint, address: String)
    {

        var query = PFUser.query()


        query?.whereKey("location", nearGeoPoint: point, withinKilometers: withinKms)
        query?.orderByAscending("location")  //MARK:  Put list in order

        query?.limit = self.limitNumberForQueryResults


        query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

            if error == nil
            {
                for(var i = 0; i < objects!.count; i++)
                {
                    let user = objects![i] as! PFUser
                    var myHomePin = MKPointAnnotation()
                    let userPoint = user["location"] as! PFGeoPoint
                    myHomePin.coordinate = CLLocationCoordinate2DMake(userPoint.latitude, userPoint.longitude)
                    myHomePin.title = user.username

                    myHomePin.subtitle = address
                    self.mapView.addAnnotation(myHomePin)

//                    self.closeUsersArray.append(user.username!) //MARK: Test

                }






//                    println("this is the array of users * \(self.closeUsersArray) *") //MARK: Test
            }
            else
            {
                println("Error: " + error!.localizedDescription)
            }

        })

    }






    // MARK: - Action Delegate

    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
    {
        switch(buttonIndex)
        {
        case 0: //Destructive button
            break
        case 1: // 25.0 Km
            //            NSUserDefaults.standardUserDefaults().setDouble(25.0, forKey: "withinKms")
            self.defaults.setDouble(50.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        case 2: // 50.0 Km
            self.defaults.setDouble(100.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        case 3: // 100.0 Km
            self.defaults.setDouble(200.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        case 4: // 200.0 Km
            self.defaults.setDouble(300.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        default:
            break;
        }
    }






    // MARK: - Actions

    @IBAction func homeAction(sender: AnyObject)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func indexChanged(sender: UISegmentedControl)
    {
        switch segmentedControl.selectedSegmentIndex
        {
        case 0:
            println("map clicked")      //MARK: this one never evaluates!
        case 1:
            self.performSegueWithIdentifier("showListView", sender: self)
            println("showListView clicked")
        default:
            break;
        }
    }




    @IBAction func radiusAction(sender: UIButton)
    {
        //        UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "cancel", destructiveButtonTitle: nil, otherButtonTitles: "25.0 Miles", "50.0 Miles", "100.0 Miles", "200.0 Miles").showInView(self.view)
        UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "cancel", destructiveButtonTitle: nil, otherButtonTitles: "50 Km", "100 Km", "200 Km", "300 Km").showInView(self.view)
    }



    @IBAction func profileButton(sender: UIBarButtonItem) {
        //        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ProfileNavControllerID") as? UIViewController
        //
        //        self.presentViewController(vc!, animated: true, completion: nil)
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ProfileNavControllerID") as! UIViewController
        self.presentViewController(vc, animated: true, completion: nil)

    }



}

以下是我的观点:

namespace Horsefly\Http\Controllers;
use profile;
use Auth;
use Illuminate\Http\Request;
use Horsefly\User;
use Horsefly\Http\Requests;     
use Horsefly\Http\Controllers\Controller;

class ProfileController extends Controller
 {
  public function profiledetails()
{


    return view('profiledetails')
    ->with('auth::user',auth::user()->get());
}

如果有人帮助我,我会很棒!!

1 个答案:

答案 0 :(得分:1)

更新控制器,

 class ProfileController extends Controller
     {
      public function profiledetails()
    {

        $users = DB::table('users')->get();
        return view('profiledetails')
        ->with('users',compact($data));
    }

查看

<ul>
   @foreach($users as $user)
    <li>

  {{$user->username}}
   </li>
   @endforeach
   </ul>
相关问题