Laravel - How to Transform Raw Query to Eloquent in Laravel - laravel

How do I transform my raw query to Laravel Eloquent
I want to transform
$games = DB::table('game_point')
->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
->paginate(15);
to
$games= new GamePoint();

To try this,
Here you change your date format in Date() function.
$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);
foreach($data as $key => $val){
$data[$key]->created_at = Date('Y-m-d',strtotime($data[$key]->created_at));
}

You can directly change it by using date() in blade or in controller depend upon your usage.
try the following code
$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);
Or In the blade or contrller you can use it just paste it where you using inside foreach
date('Y-m-d', strtotime($user->from_date));
Or you can use carbon which is already included in laravel for working with date and time.
You can read about this package here

try below:
$games = GamePoint::paginate(15);

Related

Laravel Carbon class timestamp

In my laravel project I didn't migrate the table with timestamp(created_at). I used to get the time with a date column.
I need to filter the data from that table so that I used Laravel Carbon class.
This is my function for filter the data
public function getWeeklyData()
{
$data = \Carbon\Carbon::today()->subDays(7);
$weeklydata=DB::table('response')->where('date','>=',$data)
->get();
return view('admin.pages.tables.weeklydata',['weeklydata' => $weeklydata]);
}
But there is no output.
Some times my date format is different from Carbon class date format.
If any solution for this?
When you use Carbon it will carbon object return. so try below
$data = \Carbon\Carbon::today()->subDays(7)->format('Y-m-h');
$weeklydata=DB::table('response')->where('date','>=',$data)
->get();
and you can use whereDate also
$data = \Carbon\Carbon::today()->subDays(7);
$weeklydata=DB::table('response')->whereDate('date','>=',$data)
->get();

Laravel Add Additional Rows to an Eloquent Object

I want to add an "On This Day" feature which should display records from The Previous Years. I have some Entries, all of them have a 'date' attribute. This is what I've been trying so far:
public function filterByDay($id){
$entries = Entry::where('id', $id)->get();
$currentDay = $entries[0]->date;
$oldestYear = Entry::orderBy('date','asc')->first()->date;
$previousYear = $currentDay;
while($previousYear >= $oldestYear ){
$previousYear = $currentDay->subYear();
$entries->push(Entry::where('date', $previousYear)->get());
}
return view('home')->with(compact('entries'));
}
I must send a Collection of "Entry" type from this controller method so that I can use $entry->title etc in the view. But whenever I'm using $entries->push(...) , I'm getting a Collection instance, not Entry instance. How can I convert the Collection back into Entry instance? Or what is the alternative? I'm using Laravel 5.5. Some help will be much appreciated.
You can combine whereDay, whereYear and whereMonth methods to achieve it in one liner:
$entries = Entry::where('id', $id)->get();
$today = Carbon\Carbon::now();
$oldestYear = Entry::orderBy('date','asc')->first()->date;
$allEntries = Entry::whereDay('date', $today->day)
->whereYear('date', '>=', $oldestYear)
->whereMonth('date', $today->month)
->get();
return view('home')->with(compact('allEntries'));

Laravel Query Builder in Lumen

When I use Laravel's query builder for my Lumen application with MySQL database, it does not work as expected. I used:
$itemid = DB::table('table1')->where('UserID','=',1)->pluck('ID');
This only returns one value. What is the mistake here?
Try
$itemid = DB::table('table1')->where('UserID','=',1)->get()->pluck('ID');
Here you can read more about why this happen when you use pluck on query
Pluck together with first using Query builder
Update:
I forget that DB::table returns array, so:
$items = DB::table('table1')->where('UserID','=',1)->get();
$itemsById = array_pluck($items, 'ID');
Use first instead of get as get return array.
$itemid = DB::table('table1')->where('UserID','=',1)->first()->pluck('ID');

Laravel use DB::table instead of ::find() to save or modify records

In my project I need to find some data from sql without using id in table. For example we can use this code to find data by id:
$result = BuyCard::find(10);
but I want to search in other table column such as user_code without changing laravel stucture instead if id with other column. I've tried this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data->result_transaction = 1;
$data->save();
For this code I'm getting an error but I can use it. But this code works fine:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data = BuyCard::find($data->id);
$data->result_transaction = 1;
$data->save();
how to edit this without using
$data = BuyCard::find($data->id);
between code? code is working fine but this is not correct.
Try to change this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
To:
$data = DB::table('buy_card_transactions')->where(array('transaction_id' => $key))->first();
Or:
BuyCard::where('transaction_id',$key)->first();

Laravel Eloquent "WHERE NOT IN"

I'm having trouble to write query in laravel eloquent ORM.
my query is
SELECT book_name,dt_of_pub,pub_lang,no_page,book_price
FROM book_mast
WHERE book_price NOT IN (100,200);
Now I want to convert this query into laravel eloquent.
Query Builder:
DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();
Eloquent:
SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();
You can use WhereNotIn in following way also:
ModelName::whereNotIn('book_price', [100,200])->get(['field_name1','field_name2']);
This will return collection of Record with specific fields
I had problems making a sub query until I added the method ->toArray() to the result, I hope it helps more than one since I had a good time looking for the solution.
Example
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->select('id_user')->where('id_user', '=', $id)->get()->toArray())
->get();
Query Builder:
DB::table('book_mast')
->select('book_name','dt_of_pub','pub_lang','no_page','book_price')
->whereNotIn('book_price', [100,200])->get();
Eloquent:
BookMast::select('book_name','dt_of_pub','pub_lang','no_page','book_price')
->whereNotIn('book_price', [100,200])->get();
The dynamic way of implement whereNotIn:
$users = User::where('status',0)->get();
foreach ($users as $user) {
$data[] = $user->id;
}
$available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();
You can use this example for dynamically calling the Where NOT IN
$user = User::where('company_id', '=', 1)->select('id)->get()->toArray();
$otherCompany = User::whereNotIn('id', $user)->get();
You can use WhereNotIn in the following way:
$category=DB::table('category')
->whereNotIn('category_id',[14 ,15])
->get();`enter code here`
You can do following.
DB::table('book_mast')
->selectRaw('book_name,dt_of_pub,pub_lang,no_page,book_price')
->whereNotIn('book_price',[100,200]);
Its simply means that you have an array of values and you want record except that values/records.
you can simply pass a array into whereNotIn() laravel function.
With query builder
$users = DB::table('applications')
->whereNotIn('id', [1,3,5])
->get(); //will return without applications which contain this id's
With eloquent.
$result = ModelClassName::select('your_column_name')->whereNotIn('your_column_name', ['satatus1', 'satatus2']); //return without application which contain this status.
This is my working variant for Laravel 7
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->where('id_user', $id)->pluck('id_user')->toArray())
->get();
$created_po = array();
$challan = modelname::where('fieldname','!=', 0)->get();
// dd($challan);
foreach ($challan as $rec){
$created_po[] = array_push($created_po,$rec->fieldname);
}
$data = modelname::whereNotIn('fieldname',$created_po)->orderBy('fieldname','desc')->with('modelfunction')->get();
or try pluck in laravel
here
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->where('id_user', '=', $id)->pluck('user_id'))
->get();

Resources