Laravel display table record using query

守給你的承諾、 提交于 2020-01-07 04:34:11

问题


This may be a silly question but I'm stuck..

I basically want to run a simple select query in laravel and show result from a single row in database result.

I'm new to php and laravel so trying to use model in this to get hang on MVC.

Following is what I have done. Route

Route::get('groupprofile/(:any)',array('uses'=>'groups@profile'));

Controller - groups.php

class Groups_Controller extends Base_Controller {
    public $restful=true;
    public function get_profile($groupName){
        $groups=new Groups();
        $groupInfo=$groups->getGroupInfo($groupName);
        return View::make('groups.profile.groupprofile')->with('groupInfo',$groupInfo);
    }
}

Model - groups.php

class Groups{
    public function getGroupInfo($name){
        return DB::query('select * from Groups where name=?',array($name));
    }
}

View - groupprofile.blade.php

@layout('layouts.default')
@section('content')
<h1>This is a profile page for a group.</h1>
@foreach ($groupInfo -> results as $info)
    <br />Here I want to display all columns e.g. name, philosophy, founder name etc.
    <br />$info->Description
@endforeach
<br />Testing end

@endsection

Can someone please guide me how should I do this? I'm not able to understand how to display data from passed result set in view using blade.

Or is my approach wrong to do this? I'm more comfortable in writing queries so not using Eloquent or fluent query builder.


回答1:


Look at using Eloquent in Larvel, it's the ORM. The docs are very good about this.

Your model should be Group.php

<?php class Group extends Eloquent {}

That's it! Since we are extending Eloquent, we can now in our view pull a single row like this.

Group::where('name', '=', $somevar)->first()

Of course, you'll probably want to store that in a variable in your controller and pass the object to your view.

class Groups_Controller extends Base_Controller {
    public $restful=true;
    public function get_profile($groupName){
        $groupInfo = Group::where('name', '=', $groupName)->first()
        return View::make('groups.profile.groupprofile')->with('groupInfo',$groupInfo);
    }
}

Then in your view, you can access the properties (MySQL columns) of that row like this.

$groupInfo->name


来源:https://stackoverflow.com/questions/16723984/laravel-display-table-record-using-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!