I am using Laravel 9, I stuck into the Relationship, I have a table called test_series_question another is test_series_responses. Every test_series_question has one row in test_series_responses. I need to select the responses available in the table. Something like WHERE question_id = '$id' AND test_id = $test_id
I have tried to to get the responses from Laravel Model
function response()
{
return $this->hasOne(TestSeriesResponse::class, 'question_id', 'id');
}
It's working fine, But There is a one column named test_id and if I dont compare test_id It'll return previously submitted responses which match the question_id id not the test_id
I have two questions
Can I put a parameter into function response() in Model from controller?
How can I achive the thing, Please help me out.
Here is the Controller code:
function testOngoing($test_id, $history_id)
{
$test = TestSeries::find($test_id);
$history = $history_id;
$questions = TestSeriesQuestion::where('test_id', $test_id)->with('response')->paginate(1);
$data = compact('test', 'questions', 'history');
return view('test-series/test-question')->with($data);
}
Maybe something like
$questions = TestSeriesQuestion::with(['response' => function ($query) use ($history_id) {
$query->where('history_id', $history_id);
}])->where('test_id', $test_id)->paginate(1)
I have id(Primary key) of country in multiple tables and I want to check if its value exists or not in another referenced table.
Tried using the below code but I don't think this is the right way. Can anyone please suggest something...
public function check($id)
{
$state = State::pluck('country_id');
$country = DB::select("select count(*) from country where ? not in (?)",[$id,$state]);
if($country == 0)
{
//
}
else{
//
}
}
You can check if a relationship for a record is present (or exists), using exists.
Assuming you have a relationship on your Country model called states:
public function states
{
return $this->hasMany(State::class);
}
You can check if a Country has any States related to it in your database.
// returns true if there are related states, otherwise false
Country::first()->states()->exists();
You can use whatever filtering criteria you want, so rather than first() you could use find($id) or where('field', $value) etc.
Use Exists Method here
public function check($id)
{
$state = State::pluck('country_id');
$country = DB::table('country') //table set
->whereIn('column_name',$state) //if array then used whereIn method
->where('column_name',$id) //if single value use where method
->exists();
if($country)
{
//
}
else{
//
}
}
I have a table users that has relationship to operations.
\App\user:
public function operation()
{
return $this->belongsTo('App\Operation');
}
So I can do:
$operation = user->operation
Now I want to add a Partition Metric in the Users resource page that tells me the number of users grouped by operation
Right now, it display an id, and it not filtering my users ( need to filter query with company_id )
public function calculate(NovaRequest $request)
{
return $this->count($request, User::class, 'operation_id', 'name');
}
I tried to add name column name, but first it is not working, and second, I would need the name of the operation, not the user, so it should be something like operation.name but it is not working neither.
How can I print the operation name instead of operation_id
PD: Basically, whole process it being more painful because I can't see the output of dump() or dd() in a metric, so I can't debug.
You should use ->label() method as mentioned in Laravel/nova docs:
https://nova.laravel.com/docs/3.0/metrics/defining-metrics.html#customizing-partition-labels.
Then, the correct code should be:
public function calculate(NovaRequest $request)
{
return $this->count($request, User::class, 'operation_id')
->label(function($operationId){
switch($operationId){
case 'opration_1_id': return 'operation_1_name';
break;
case 'opration_2_id': return 'operation_2_name';
break;
default: return 'Other';
}
});
}
I want to get all data in one column of the database (primary key) so that before I insert my data that is going to be inserted, I can check if its going to be duplicate or not.
Model:
public function getKeys() {
$this->db->select("key");
$this->db->from("database");
$result = $this->db->get();
return $result->result();
}
Controller:
public function Controler() {
$values = $this->MODEL_NAME->getKeys();
foreach ($values as $value) {
$array[] = $value->key;
}
# Compare new item to the current array
if (!(in_array($NEWITEM, $array))) {
# Insert
} else {
# Error catching
}
}
At insert time get all data from table.and then use condition on a particular field by which you want to check this data is already exist or not:
Using select2 with a Laravel / Vue project and need to return JSON in the following format:
[
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' }
]
In Laravel I know I can use pluck to create my list data e.g. for customers:
$customers = Customer::pluck('id', 'first_name');
But Want to return the id and first name + last name as a single name.
How can I do this?
Have you tried using Accessors?
https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
I have not tested it but this could work:
add this to your Customer Eloquent Model:
public function getFullNameAttribute()
{
return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
}
and then try:
UPDATED pluck on accessor will only work on a collection. If you try Customer::pluck('id', 'full_name') it will not work since there is no db column named full_name, therefore you must use Customer::all()->pluck('full_name', 'id')
$customers = Customer::all()->pluck('full_name', 'id');
as a side note, for performance it is probably better to do Customer::all(['id', 'first_name', 'last_name'])->pluck(...) so that we don't pull unnecessary columns from the db.
Hope this helps.
Updated Date:- 26th Aug, 2021
If we use computed Attribute accessor functionality, then mind it one important thing...
Laravel Accessor functionality works after the Data fetched from DataBase. So we have to declare "pluck(accessorName)" at the end of Query....
For Example:-
Wrong Methods:-
$data = Model::pluck('full_name','id)->get();
$data = Model::pluck('full_name','id)->all();
in above two queries if you does not have full_name field in DataTable you will get Unknown column error
Right Methods:-
$data = Model::get()->pluck('full_name','id');
$data = Model::all()->pluck('full_name','id');
in above two queries it will works perfectly even if you doesn't have full_name field in DataTable
You can do it like this,
$customers = DB::table('customers')->select("id", "CONCAT(firstname,' ',lastname) as fullname")->get();
or you also do like this,
$customers = DB::table('customers')->select(DB::raw('CONCAT(firstname,' ',lastname) as fullname, id'))->get();
or with PHP way,
$fullname = $customers->firstname. " " .$customers->lastname;
Set this in the User model
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
Then make sure you add this too
protected $appends = ['full_name'];
For me it worked
\DB::table("admin as c")->select(\DB::raw("CONCAT(FirstName, ' ', LastName) AS FIRSTNAME"),"c.AdminID")->pluck("FIRSTNAME","AdminID");
Use this code. Hope it will work. And I solve this problem using this code
User::select(DB::raw("CONCAT(first_name, ' ', last_name) AS full_name"),"id")->pluck("full_name","id");
User Model :
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
Get query will result in collection :
$agents = User::whereId($agent->id)->get()->pluck('full_name', 'id');
Inorder to convert variable from objects to array :
$agents = json_decode(json_encode($agents), true);
It worked for me.Enjoy.
/**
* Get the full name of the user.
*
* #return string
*/
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
and use this pluck
User::all()->sortBy('id')->pluck('full_name', 'id')
like this
public static function list()
{
return Cache::tags('usersCustomers')->rememberForever(md5('usersCustomers.list:' . locale()), function () {
return self::all()->sortBy('id')->pluck('full_name', 'id');
});
}
** Use this code. Hope it will work. And I solve this problem using this code**
User::select(DB::raw("CONCAT(first_name, ' ', last_name) AS
full_name"),"id")->pluck("full_name","id");