How can I get specific column fields? - laravel

I want return specific columns for every card that is returned by eloquent relationship.
I can do it with ->get(['column1', 'column2']) but in this situation I can't use get().
Is there a solution for this ?
$deckId = $request->deckId;
$deck = Deck::find($deckId);
return $deck->cards;
on the cards I want for example just the id the name and the card_type

This code should work if you already defined the relationship
return $deck->cards()->get(['id', 'name', 'card_type']);

Have you looked into pluck?
Deck::all()->pluck('column1', 'column2');
This will return an array with column1 as key and column2 as value

Related

How to sum of column in laravel with relationship

How to sum of duration column where my course id or section id is same
Try this code:
$res = Model::groupBy('course_id', 'section_id')
->selectRaw('sum(duration) as total_duration, course_id, section_id') // do the sum query here
->pluck('total_duration','course_id', 'section_id'); // get the related query column here
Source answer
You have to use hasMany relation on this table with course and section table.
For hasMany relation see this docs. Here
Then, you can use foreach to generate the sum.
$summation = $yourtablenames->sum(function ($yourtablename) {
return $yourtablename->your_relation_name->sum('duration');
});

Find max value of a column in laravel

The problem started because I have a table (Clientes), in which the primary key is not auto-incremental. I want to select the max value stored in a column database.
Like this select, but with eloquent ORM (Laravel):
SELECT MAX(Id) FROM Clientes
How can I do this?
I tried:
Cliente::with('id')->max(id);
Cliente::select('id')->max(id);
I prefer not to make a simple raw SELECT MAX(ID) FROM Clientes
I cannot make it.
Thanks all!
The correct syntax is:
Cliente::max('id')
https://laravel.com/docs/5.5/queries#aggregates
Laravel makes this very easy, in your case you would use
$maxValue = Cliente::max('id');
But you can also retrieve the newest record from the table, which will be the highest value as well
$newestCliente = Cliente::orderBy('id', 'desc')->first(); // gets the whole row
$maxValue = $newestCliente->id;
or for just the value
$maxValue = Cliente::orderBy('id', 'desc')->value('id'); // gets only the id
Or, if you have a created_at column with the date you could get the value like this
$maxValue = Cliente::latest()->value('id');
Relevant Laravel Documentation: https://laravel.com/docs/5.5/queries#aggregates
$maxValue = DB::table('Clientes')->max('id');
Cliente::where('column_name', $your_Valu)->max('id') // You get any max column
We can use the following code :
$min_id = DB::table('table_name')->max('id');
https://laravel.com/docs/8.x/queries#aggregates

How to get unique year values from created_at?

I have a collection called $products, each instance of which has a field created_at. The latter obviously has a format ('Y-m-d H:i:s') in the DB. Now, it's easy to get instances with unique created_at. However, I'd like to retrieve unique year values of created_at in one single expression (that I can write in my view). What I am looking for is:
$products->unique( year value ('Y' ONLY) of 'created_at' )
This expression should evaluate to something like this: ['2012', '2013', '2016'].
Building on the comment that gives you a collection with unique timestamps, you can map out the year and sort with the following code.
$years = $products->unique(function($item){
return $item['created_at']->year;
})->map(function($item){
return $item['created_at']->year;
})->sort()->toArray();
In addition to Tim result
$products = DB::table('products')->get();
$years = $products->unique(function($item){
return $item['created_at']->year;
})->map(function($item){
return $item['created_at']->year;
})->sort()->toArray();
You can use toArray or values() to get the result of collection

How to select specific columns in laravel eloquent

lets say I have 7 columns in table, and I want to select only two of them, something like this
SELECT `name`,`surname` FROM `table` WHERE `id` = '1';
In laravel eloquent model it may looks like this
Table::where('id', 1)->get();
but I guess this expression will select ALL columns where id equals 1, and I want only two columns(name, surname). how to select only two columns?
You can do it like this:
Table::select('name','surname')->where('id', 1)->get();
Table::where('id', 1)->get(['name','surname']);
You can also use find() like this:
ModelName::find($id, ['name', 'surname']);
The $id variable can be an array in case you need to retrieve multiple instances of the model.
By using all() method we can select particular columns from table like as shown below.
ModelName::all('column1', 'column2', 'column3');
Note: Laravel 5.4
You first need to create a Model, that represent that Table and then use the below Eloquent way to fetch the data of only 2 fields.
Model::where('id', 1)
->pluck('name', 'surname')
->all();
Also Model::all(['id'])->toArray() it will only fetch id as array.
Get value of one column:
Table_Name::find($id)->column_name;
you can use this method with where clause:
Table_Name::where('id',$id)->first()->column_name;
or use this method for bypass PhpStorm "Method where not found in App\Models":
Table_Name::query()->where('id','=',$id)->first()->column_name;
in query builder:
DB::table('table_names')->find($id)->column_name;
with where cluase:
DB::table('table_names')->where('id',$id)->first()->column_name;
or
DB::table('table_names')->where('id',$id)->first('column_name');
last method result is array
You can use get() as well as all()
ModelName::where('a', 1)->get(['column1','column2']);
From laravel 5.3 only using get() method you can get specific columns of your table:
YouModelName::get(['id', 'name']);
Or from laravel 5.4 you can also use all() method for getting the fields of your choice:
YourModelName::all('id', 'name');
with both of above method get() or all() you can also use where() but syntax is different for both:
Model::all()
YourModelName::all('id', 'name')->where('id',1);
Model::get()
YourModelName::where('id',1)->get(['id', 'name']);
To get the result of specific column from table,we have to specify the column name.
Use following code : -
$result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();
for example -
$result = DB::Table('Student')->select('subject','class')->where('id',1)->get();
use App\Table;
// ...
Table::where('id',1)->get('name','surname');
if no where
Table::all('name','surname');
If you want to get a single value from Database
Model::where('id', 1)->value('name');
Also you can use pluck.
Model::where('id',1)->pluck('column1', 'column2');
You can use Table::select ('name', 'surname')->where ('id', 1)->get ().
Keep in mind that when selecting for only certain fields, you will have to make another query if you end up accessing those other fields later in the request (that may be obvious, just wanted to include that caveat). Including the id field is usually a good idea so laravel knows how to write back any updates you do to the model instance.
You can get it like
`PostModel::where('post_status', 'publish')->get(['title', 'content', 'slug', 'image_url']`)
link
you can also used findOrFail() method here it's good to used
if the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these method not give a 500 error..
ModelName::findOrFail($id, ['firstName', 'lastName']);
While most common approach is to use Model::select,
it can cause rendering out all attributes defined with accessor methods within model classes. So if you define attribute in your model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the user's first name.
*
* #param string $value
* #return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
And then use:
TableName::select('username')->where('id', 1)->get();
It will output collection with both first_name and username, rather than only username.
Better use pluck(), solo or optionally in combination with select - if you want specific columns.
TableName::select('username')->where('id', 1)->pluck('username');
or
TableName::where('id', 1)->pluck('username'); //that would return collection consisting of only username values
Also, optionally, use ->toArray() to convert collection object into array.
If you want to get single row and from the that row single column, one line code to get the value of the specific column is to use find() method alongside specifying of the column that you want to retrieve it.
Here is sample code:
ModelName::find($id_of_the_record, ['column_name'])->toArray()['column_name'];
If you need to get one column calling pluck directly on a model is the most performant way to retrieve a single column from all models in Laravel.
Calling get or all before pluck will read all models into memory before plucking the value.
Users::pluck('email');
->get() much like ->all() (and ->first() etc..) can take the fields you want to bring back as parameters;
->get/all(['column1','column2'])
Would bring back the collection but only with column1 and column2
You can use the below query:
Table('table')->select('name','surname')->where('id',1)->get();
If you wanted to get the value of a single column like 'name', you could also use the following:
Table::where('id', 1)->first(['name'])->name;
For getting multiple columns (returns collection) :
Model::select('name','surname')->where('id', 1)->get();
If you want to get columns as array use the below code:
Model::select('name','surname')->where('id', 1)->get()->toArray();
If you want to get a single column try this:
Model::where('id', 1)->first(['column_name'])->column_name;

Select one column with where clause Eloquent

Im using Eloquent. But I'm having trouble understanding Eloquent syntax. I have been searching, and trying this cheat sheet: http://cheats.jesse-obrien.ca, but no luck.
How do i perform this SQL query?
SELECT user_id FROM notes WHERE note_id = 1
Thanks!
If you want a single record then use
Note::where('note_id','1')->first(['user_id']);
and for more than one record use
Note::where('note_id','1')->get(['user_id']);
If 'note_id' is the primary key on your model, you can simply use:
Note::find(1)->user_id
Otherwise, you can use any number of syntaxes:
Note::where('note_id', 1)->first()->user_id;
Note::select('user_id')->where('note_id', 1)->first();
Note::whereNoteId(1)->first();
// or get() will give you multiple results if there are multiple
Also note, in any of these examples, you can also just assign the entire object to a variable and just grab the user_id attribute when needed later.
$note = Note::find(1);
// $user_id = $note->user_id;

Resources