i'm using Laravel 5.3
and i'm trying to select from the database the values for the lang files,
i created a file and named it global.php
and inside the file i tried to do this:
use App\Dictionary;
$language_id = 1;
$dictionary = array();
$lables = Dictionary::where('language_id',$language_id)->get();
foreach($lables as $label):
$dictionary[$label->label] = $label->value;
endforeach;
return $dictionary;
now, this is working but i want to select the rows using the short_name field and not the id of the language
i want it to be something like this:
$lables = Dictionary::all()->language()->where('short_name', 'en')->get();
my database looks like this:
Languages
id
name // for example: English
short_name // for exmaple: en
Dictionary
id
key
value
language_id
and my models looks like this:
Language Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Language extends Model
{
use SoftDeletes;
protected $softDelete = true;
protected $dates = ['deleted_at'];
public function dictionary()
{
return $this->hasMany('App\Dictionary');
}
}
Dictionary Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Dictionary extends Model
{
protected $table = 'dictionary';
public function language()
{
return $this->belongsTo('App\Language');
}
}
thank you for your help!
!!!UPDATE!!!
i added 1 more table called
Labels
id
label_name
and change the dictionary table to:
Dictionary
id
lable_id
value
language_id
how can i make this work so i can pull the label_name instead of the label_id
$lables = Dictionary::whereHas('language', function($query) {
$short_name = basename(__DIR__);
$query->where('short_name', $short_name);
})->pluck('value', 'label_id')->toArray();
You can use Laravel's whereHas() function as:
$lables = Dictionary::whereHas('language', function($query) {
$query->where('short_name', 'en');
})->get();
Update
If you want to get rid of your foreach() then you can use Laravel's pluck() function as:
$lables = Dictionary::whereHas('language', function($query) {
$query->where('short_name', 'en');
})->pluck('value', 'label')->toArray();
I guess it could be something like:
$lables = Dictionary::with('language')->where('short_name', 'en')->get();
Related
Im new to laravel, i am trying to query a specific table in my DB. I only have 1 data table and the standard user auth tables. I am getting a error: BadMethodCallException
Call to undefined method App\Figures::table().
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Figures extends Model
{
}
controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Figures;
class figuresController extends Controller
public function figurespag2() {
$dummyDetails = Figures::table('figures')->where('name', 'batman');
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
route
Route::get ( '/pagination2', 'figuresController#figurespag2' );
I know it's going to be something obvious, but I am new to this.
this is wrong
$dummyDetails = Figures::table('figures')->where('name', 'batman');
Method 1---------- laravel eloquent
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Figures extends Model
{
protected $table = 'figures';
}
Controller
$dummyDetails = Figures::where('name', 'batman')->get();
and
Method 2 ---------- laravel Query Builder
$dummyDetails = \DB::table('figures')->where('name', 'batman')->get();
Use this you not need to define table name
public function figurespag2() {
$dummyDetails = Figures::where('name', 'batman')->get();
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
First you may need to know laravel model rules.
If you create a table name like "figures" (plural) you need to create its model by Figure (singular).
if you create a table other then this rule then you have to mentioned table name in model like this.
protected $table = "table_name";
you can access table with where condition in controller like this.
public function figurespag2() {
$dummyDetails = Figure::where('name', 'batman')->get();
return view ( 'pagination2.index' )->withUsers($dummyDetails);
}
Hope this may help you.
Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.
Here is my model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
}
Here is my Controller Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
class GetController extends Controller
{
public function databybusinessid($business _id){
$users = new user();
$users = user::find($business _id);
return response()->json($users);
}
}
Thank you so much
You are using user::find($business _id)
find() method will automatically search by the primary key but none is defined in your model and Eloquent can't decide which one to pick from your table. Therefore, you should explicitly set your primary key in your model by adding the following line.
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
If in doubt, you can also fetch database record by a specific column using where
$users = user::where('business_id', '=', $business _id)->get()
Laravel documentation about Eloquent ORM
https://laravel.com/docs/5.8/eloquent
find() Retrieve a model by its primary key..
So you have to use your code as:
$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...
Or you can change your primary code in model
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
find() works only on primary key. you need to use where instead.
or you can define business_id as primary key in your User model.
protected $primaryKey = 'business_id';
public function databybusinessid($business _id){
$users = new user();
$users = user::where('business_id',$business _id)->first();
return response()->json($users);
}
I'm using laravel-eloquent and want to return a collection that joins several tables. For now, I do this using the query builder join method, but I would like to stay within eloquent. I mean, I already defined all my relationships, why should I write joins with foreign keys all the time?
For example, if I have defined my models like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function comments()
{
return $this->hasMany('App\Comments');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
and want to return all the comments with the user names, for now I would write this:
DB::table('users')->select('users.name', 'comments.body')
->join('comments', 'users.id', '=', 'user_id')
->get();
I have tried writing
$users = new 'App\User';
$users->with('comments')
->select('name', 'comments.body');
but it didn't work. Do I need to define a new collection? I will end up with many, many collections if I do that...
Try:
$result = null;
$users = new 'App\User';
$records = $users->with('comments')->get();
if ($records->isNotEmpty()){
$result = $records->map(function($val,$key){
return ["name"=>$val->name, "comments" => $val->comments()->get(['body']);
})->values()->all();
}
dd($result);
I have not tested the codes yet. Please check and let me know if it works for you?
im sory, im noob in laravel. later, im build web just use php native, and i have code like this
$query1 = select * from user where id='$id';
while($data1 = mysql_fetch_array($query1){
$query2 = select * from komen where iduser=$data['id'];
}
so to convert to laravel be what.
I already read the documentation laravel but did not find
Where id = $id should only return 1 value (given that id is your unique primary key), so you would never have to loop through the result of your $query1, it's just 1 or nothing.
Best thing you can do to fetch the related Komen is to setup a relation in the model. For more info see: https://laravel.com/docs/5.3/eloquent-relationships
Best option for you is to create the User model first (already exists after Laravel installation) and add the komens() relation (1:n)
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'user'; // should be users
// define has many relationship
public function komens()
{
// you will have to set userid, as laravel searches for user_id (singular tablename _ key)
return $this->hasMany(Komen::class, 'userid');
}
}
Then create the Komen model (check your naming conventions, laravel looks for the table name as the lowercase snake_cased plural version of your model name, so in this case komens. If you want to overwrite this, you have to set the protected $table = 'komen';
use Illuminate\Database\Eloquent\Model;
class Komen extends Model
{
protected $table = 'komen'; // should be komens
// define the inverse of the user model's komens() method
public function user()
{
return $this->belongsTo(User::class, 'userid');
}
}
Now in your code you can do something like this:
// fetch the user by id
$user = User::find($id);
// check if user exists
if ($user) {
// fetch all related komens from the database and loop through the collection
$user->komens->each(function($komen) {
// do foo here
dump($komen);
});
}
Check out the Eloquent ORM documentation here: https://laravel.com/docs/5.3/eloquent
First create the UserModel and KomenModel.
then use this
$queryData = UserModel::find($id);
foreach ($queryData as $data) {
$query2 = KomenModel::find($data->id);
}
or instead of above code you can do this using laravel join query.
There are two way of creating Queries...
1.Query...using normal DB::table...
2.Eloquent Model...
description
1.
`$data = DB::table('Tablname')->where('id',$id)->all();`
in here USE DB;
and there are severl methods such as all() , get()
2.
$this->model->where($attrib, '=', $value)->get();
where we go from the model option...
But as i understood you can go with DB query method..
$result= DB::table('komen')->where('id', $id)->all();
//check the previous query have got any data...
if($result)
{
//go for the second Query.....
}
If there is any need just mention...I am also new to laravel 5.3
You can get by following code without use any model.
$Data = DB::table('user')->where('id', '=', $id)->get();
foreach ($Data as $data) {
$query2 = DB::table('komen')->where('iduser', '=', $data->id)->get();
}
I am trying to use laravel 5.1 to select records from MySQL database and break the results into pages.
Here is the method that I use to return the database results to the listall view. (This code display white screen "no errors, no results")
public function getIndex(){
$accounts = DB::table('accounts')
->lists('account_id','account_name')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
When using this code below, it works but it returns all the column. I only want to display 2 columns.
public function getIndex(){
$accounts = DB::table('accounts')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
EDITED
This is my code after Kyle Suggestion "below"
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Accounts;
class AccountsController extends Controller
{
public function getIndex(){
$accounts = Accounts::select('account_id', 'account_name')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
public function getAccounts($id){
return view('accounts.account')->withName('Mike A');
}
}
This is my Accounts Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Accounts extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'accounts';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['account_id', 'account_name', 'company_code'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [];
}
But I still get a white screen
First off, you shouldn't be using DB::table('accounts'). You should be using Account::all(). It's just syntax though I guess.
I assume you have a table named accounts with 2 columns of that table being account_id and account_name. That being said, your whole class should look similar to this:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Account; //don't forget this so you can use it below
class AccountController extends Controller {
public function getIndex() {
$accounts = Account::select('account_id', 'account_name')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
Is that what you need?
In the Laravel Query Builder docs, see "Specifying a Select Clause". To do what you are trying to do, you need to use the select method instead of the lists method you are using.
The select method allows you to specify which columns you want from the table, and returns $this (The Query Builder instance) so that you can chain it with more Query Builder methods like you are doing with where and paginate.
The lists method returns an array (see in the docs under "Retrieving A List Of Column Values"). The returned array will not have the where and paginate methods. This is what is currently killing your script and giving you the white screen.
The lists method should be the last method called in a chain of query builder methods. Like get or paginate, it is meant to return the results of your query in a specific way.