laravel4 select all data from other table by relation(one to many) - php

i have two tables users its model (User) ... and servs it model (servs) .... the relation is one to many .... when i try to select all sevices with belong to one user .... it select first service only and ignore others ... this is code i used it
public function getserv(){
return View::make('infos.serv');
}
public function postserv(){
$user = User::find(Auth::user()->id);
$user_id = $user->id;
$serv = servs::where('user_id','=',$user_id);
if($serv->count()){
$serv = $serv->get();
//return $serv->user_id;
foreach ($serv as $servs) {
return $servs->serv_id;
}
}
}

Instead of returning the data at the first loop, you should better do something like this:
$result = array();
foreach ($serv as $servs) {
$result[] = $servs->serv_id;
}
return $result;

Try this.
public function postserv(){
$user = User::find(Auth::user()->id);
$user_id = $user->id;
$serv = servs::where('user_id','=',$user_id)->get()->first;
if($serv)
return $serv->serv_id;
else
return null;
}

You only see the first one because when you return something the function ends and the rest of $serv doesn't get processed.
I recommend you first set up Eloquent relations properly
class User extends Eloquent {
public function servs(){
return $this->hasMany('servs');
}
}
After that you can retrieve all servs for a user like this:
$user = Auth::user();
$servs = $user->servs;
foreach ($servs as $serv) {
echo $serv->serv_id;
}

Related

I cannot access model methods when using DB Facade in laravel

I have this model and I don't want to use eloquent due to some performance and slow query, even though I'm using Eager Loading the performance changes little bit. But unlike DB Facade the query is much faster. My problem is how can I access the method inside my model by using DB Facade?
----------------------
Table: user
id | fname | lname
-----------------------
and this is my model
class User extends Model {
public function complete_name() {
return $this->fname . " ".$this->lname;
}
}
but when Im using
$users = DB::table('user')->get();
and loop through it
$result = [];
foreach ($users as $user) {
$result[] = $user->complete_name();
}
return $result;
I cannot access the method "complete_name()". Is there any techniques or style in order for me to access the method inside User class?
your model User.php
class User extends Model {
public function complete_name() {
return $this->fname . " ".$this->lname;
}
}
You can also use like this
use App\User;
$users = User::all();
Then You can access your complete_name() method.
$result = [];
foreach ($users as $user) {
$result[] = $user->complete_name();
}
return $result;
there is no need to call the complete_name method on there, because the Query builder not return model. you can write your code like below:
$users = DB::table('user')->get();
your loop could be like:
$result = [];
foreach ($users as $user) {
$result[] =$user->fname.' '. $user->lname;
}
return $result;
For using methods in model you must use eloquent instead query builder
Like first answer
otherwise
public function index(){
$users = DB::table('user')->get();
$result = [];
foreach ($users as $user) {
$result[] = $this->complete_name($user);
}
return $result;
}
public function complete_name($user) {
return $user->fname . " ".$user->user;
}

How to get ID from a relationship table, Laravel

I have 4 table : Users, CompanyRegister, VoucherDetails, Addvoucher.
So the Authenticate Users Id will be submit as user_id in companyRegister table,and then companyRegister ID will be submit as company_id in Voucherdetails table, and lastly voucherDetails Id will be submit in addVoucher table as voucher_ID. I am new to using eloquent and also laravel, I cant understand why I cant get the id from voucherdetails and submit in addvoucher but I can get id from companyregister and submit in company_id in voucherdetails. I'm using the same method to get id but not work, I hope can get solution and explanation here,Thank you in advance!!
My users model
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
public function addvoucher()
{
return $this->hasMany('App\addvoucher');
}
public function roles()
{
return $this->belongsToMany('App\role');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
my companyregister model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
my voucherdetails model
public function User(){
return $this->belongsTo('User');
}
public function companyregisters(){
return $this->belongsTo('App\companyregisters');
}
public function addvoucher()
{
return $this->hasOne('App\addvoucher');
}
my addvoucher model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails(){
return $this->belongsTo('App\voucherdetails');
}
my voucherdetailsController
public function store(Request $request){
$voucherdetail = new voucherdetails();
$voucherdetail->title = $request->input('title');
$voucherdetail->description = $request->input('description');
$voucherdetail->user_id = Auth::user()->id;
$id = Auth::user()->id;
$user = User::find($id);
$company = $user->companyregisters;
$companyId = $company->id;
$voucherdetail->company_id = $companyId;
$voucherdetail->save();
return redirect()->to('addvoucher');
}
my addvoucherController
public function store(Request $request){
$addvoucher = new addvoucher();
$addvoucher->voucherTitle = $request->input('voucherTitle');
$addvoucher->voucherCode = $request->input('voucherCode');
$addvoucher->user_id = Auth::user()->id;
//Here(the voucherdetails id cant get to submit in voucher_id)
$id = Auth::user()->id;
$user = User::find($id);
$voucher = $user->voucherdetails;
$voucherID = $voucher->id;
$addvoucher->voucher_id = $voucherID;
$addvoucher->save();
return redirect()->to('displayVouchers');
}
This code works because companyregisters is a hasOne relationship for which the docs say:
Once the relationship is defined, we may retrieve the related record
using Eloquent's dynamic properties.
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
$company = $user->companyregisters; // ie this returns the single related record
$companyId = $company->id; // and it has an `id` property, all good here
However, this code fails because voucherdetails is a hasMany relationship for which the docs say:
Once the relationship has been defined, we can access the "collection"
of comments by accessing the comments property.
More info on collections
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
$voucher = $user->voucherdetails; // ie this returns a "collection" of related records
$voucherID = $voucher->id; // this "collection" does NOT have an id property, but each record IN the collection does.
In summary, either your relationship is defined incorrectly (hasMany vs hasOne) or, you'll need to loop over the related records to get the id from each.

No database entries when iterate array from database Laravel

protected function show()
{
$users = User::all();
$letters = Letter::with('user');
$userLetter = $letters->where(['user_id' => 2])->count();
//Here function work right. Shows that we have 10 users
foreach ($users as $user) {
$userLetter = $letters->where(['user_id' => $user->id])->first();
if($userLetter){
//Here it shows that only the first user exists, returns null for the rest users.
}
}
}
We get an error when we sort the array with foreach.
No record is found in the database except the first.
For other entries, return null.
outside foreach no errors.
Just move your object inside the loop like below.
protected function show()
{
$users = User::all();
$userLetter = $letters->where(['user_id' => 2])->count();
//Here function work right. Shows that we have 10 users
foreach ($users as $user) {
$userLetter = Letter::with('user')->where(['user_id' => $user->id])->first();
if($userLetter){
}
}
}
You would probably be better off using a letter relationship on the User.
On the User model you could do something like :
public function letter()
{
return $this->hasOne(Letter::class, 'user_id');
}
Then you could in the controller:
protected function show()
{
$users = User::with('letter')->get();
foreach ($users as $user) {
if ($user->letter) {
// do things
}
}
}

get many to many with where clause in laravel

I Have this 3 tables like below :
Tools
Parts
Part_details
it is my the table structure :
Tool -> has many -> parts. part -> has many->part_details.
Tool : id*, name; Parts : id*, name, tool_id; part_details: id, part_id, total;
Question :
Using laravel Model, how can I get Tool with One part that has biggest total on parts_details ??
// Tool Model
public function parts(){
return $this->hasMany(Part::class);
}
// Part Model
public function part(){
return $this->belongsTo(Tool::class);
}
public function part_details(){
return $this->hasMany(PartDetail::class);
}
// PartDetail Model
public function part(){
return $this->belongsTo(Part::class);
}
Now query the Tool model
$tools = Tool::with('parts')->withCount('parts.part_details')->get();
$toolWithMaxCount = $tools->filter(function($tool) use ($tools){
return $tool->parts->max('par_details_count') === $tools->max('parts.part_details_count');
})->first();
You can improve this with adding some raw bindings to optimise it. I think you got the idea.
Tool model
public function parts() {
return $this->hasMany('App\Part');
}
Part Model
public function details() {
return $this->hasMany('App\PartDetail');
}
public function tool() {
return $this->belongsToMany('App\Tool');
}
Detail Model
public function part() {
return $this->belongsToMany('App\Part');
}
Controller
$tools = Tool::with('parts', 'parts.details')
->find($id)
->max('parts.part_details');
Use the the hasManyThrough Relationship to get the all part details related to tool and then you can check the one by one record and get the highest total of the tool part.
// Tool Model
public function partsdetails()
{
return $this->hasManyThrough('App\PartDetail', 'App\Part','tool_id','part_id');
}
In Your controller
$data = Tool::all();
$array = [];
if(isset($data) && !empty($data)) {
foreach ($data as $key => $value) {
$array[$value->id] = Tool::find($value->id)->partsdetails()->sum('total');
}
}
if(is_array($array) && !empty($array)) {
$maxs = array_keys($array, max($array));
print_r($maxs);
}
else{
echo "No Data Available";
}

How to properly load a Database row into a class in php

I am using Kohana 3.2, not that it matters much, but I am writing an application where I am wrapping any and all returned database records in a specific class. I don't know that I understand the best way to load the database row into the class, because sometimes it is a ORM model and sometimes it might just be an row ID.
So from a controller if I wanted a list of all the users it would look something like:
Controller:
$users = User::find_all();
User Class
public static function find_all()
{
$users_model = ORM::factory('user')->find_all();
$users = array();
foreach ($users_model as $user_model)
{
$users[] = User::instance($user_model);
}
return $users;
}
That works great, but sometimes I need to load a user object with just an id, like after some action, again a example:
Controller
$user_id = $_POST['user_id'];
$user = User::instance($user_id);
So is the User class responsible for trying to identify if an ID or a ORM object was passed into it. It seems like that isn't right for good OOP practices, but I am really not sure what the best way to do it is. What I have been currently doing is in the construct:
public function __construct($user, $load = 'model')
{
if ($load == 'model')
{
$this->user_model = $user;
}
if ($load == 'id')
{
$this->user_model = ORM::factory('user', $user);
}
}
But that really just doesn't feel right. Any advice would be greatly appreciated.
If you already have a user model that extends ORM then you probably don't need static methods in the class to get all users or to get a particular user.
In your controller you can just do to get all the users
$users = ORM::factory('user')->find_all();
To get a single user
$user = ORM::factory('user', $user_id);
If you still want to go down the wrapping route you could use functions like so
public static function all() {
$users = ORM::factory('user')->find_all();
if (count($users)) {
return $users;
}
return false;
}
public static function get($user_id) {
$user = ORM::factory('user', $user_id);
if ($user->id) {
return $user;
}
return false;
}
In your controller, use the ORM to get the user based on the ID.
$user_id = $_POST['user_id'];
$user = ORM::factory('user', $user_id);
Or given that you already have a find all in your user class, add a find_one() method:
User Class
public static function find_one($user_id)
{
$user = ORM::factory('user', $user_id);
return $user;
}
Controller
$user_id = $_POST['user_id'];
$user = User::find_one($user_id);
See the Kohana docs.
http://kohanaframework.org/3.1/guide/orm/using#finding-an-object
http://kohanaframework.org/3.1/guide/orm/examples/simple
Maybe like this:
public function __construct($user)
{
$this->user_model = is_object($user) ? $user : ORM::factory('user', (int)$user);
}

Categories