Laravel Add Additional Rows to an Eloquent Object - laravel

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'));

Related

Laravel Eloquent Only Get One Row

So I want to show id from order table where user id is the same as currently login user id, then later used to show orders have been made by the user
$orderId = Order::select('id')->firstWhere('user_id', auth()->id())->id;
$orders = SubOrder::where('order_id', $orderId)->orderBy('created_at', 'desc')->get();
it works but it only shows the first record, after some digging later I found out that the problem is on the $orderId, it only shows the first record. but I want it to be all the records. if I change the id to get(), it shows nothing since it give the result like "id = 1" instead of the number only. also have tried to change the firstWhere into where and got error like "Property [id] does not exist on the Eloquent builder instance."
please help, thanks
If you are going to use the other Orders associated with the User soon after you get the first Order, return all the relevant Orders and then just grab the first one when you need it.
$orders = Order::where('user_id', auth()->user()->id)->get();
$firstOrder = $orders->first();
$subOrders = SubOrder::whereIn('order_id', $orders->pluck('id'))->get();
Alternatively, you could use a subOrders relationship defined on your Order model.
class Order extends Model
{
public function subOrders()
{
return $this->hasMany(SubOrder::class);
}
}
$orders = Order::where('user_id', auth()->user()->id)->get();
$firstOrder = $orders->first();
$firstOrderSubOrders = $firstOrder->subOrders;
If you're confident you're going to be working with SubOrder records, you can use eager loading on your Order to improve performance.
$orders = Order::where('user_id', auth()->user()->id)
->with('subOrders')
->get();
$firstOrder = $orders->first();
$firstOrderSubOrders = $firstOrder->subOrders;
first() will return the first id queried and stop execution.
$firstOrder = $orders->first();

Looking up model in Laravel after returning array of objects in Controller

I am trying to do something I've never done before in Laravel and cannot figure out how to do it.
I have the following code in my Controller:
public function show($id)
{
//Get application for drug
$application = PharmaApplication::where('ApplNo', $id)->first();
//Get all products for given application (i.e. the different quantities and forms drug comes in)
$product = PharmaProduct::where('ApplNo', $id)->get();
foreach($product as $product){
$product->ProductNo;
}
//Get Marketing Status for drug
$marketingStatus = DB::table('pharma_marketing_statuses')
->where('ApplNo', $id)
->where('ProductNo', $product->ProductNo)
->get();
//Lookup marketing status Description
$marketingStatusDescription = PharmaMarketingSatusLookup::where('MarketingStatusID', $marketingStatus->MarketingStatusID);
return view('profiles.drug', compact('application', 'product', 'marketingStatus', 'marketingStatusDescription'));
}
I am trying to accomplish the following:
Get the application for a drug - this part of my code works
Return an array of objects for the products (i.e. 7 products that belong to one application). I can do this but get stuck going to the next part.
Next, I have to use the array of objects and search a table with the following columns: MarketingStatusID, ApplNo, ProductNo. I know how to query this table and get one row, but the problem is I have an array that I need to search. I imagine I have to use a loop but don't know where.
Finally, I use the MarketingStatusID to retrieve the MarketingStatusDescription which I will know how to do.
I am also getting an error message that says:
Class 'App\Http\Controllers\profiles\PharmaMarketingSatusLookup' not found
In my Controller, I have use App\PharmaMarketingStatusLookup; so I am not sure why it is searching the Controllers folder
You have a typo in your class
From PharmaMarketingSatusLookup change to PharmaMarketingStatusLookup
App\Http\Controllers\profiles\PharmaMarketingStatusLookup
USE whereIn
use App\PharmaApplication;
use App\PharmaProduct;
use App\PharmaMarketingSatusLookup;
public function show($id)
{
$application = PharmaApplication::where('ApplNo', $id)->first();
$products = PharmaProduct::where('ApplNo', $id)->get();
$productid = array();
foreach($products as $product){
$productid[] = $product->ProductNo;
}
$marketingStatus = DB::table('pharma_marketing_statuses')
->where('ApplNo', $id)
->whereIn('ProductNo', $productid)
->get();
$marketingStatusDescription = PharmaMarketingSatusLookup::where('MarketingStatusID', $marketingStatus->MarketingStatusID);
return view('profiles.drug', compact('application', 'product', 'marketingStatus', 'marketingStatusDescription'));
}

Laravel simplePaginate() for Grouped Data

I have the following query.
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);
When I try to paginate with the simplePaginate() method I get this error.
stripos() expects parameter 1 to be string, object given
How can I paginate grouped data in this case?
The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:
$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
return $project->created_at->format('Y-m-d');
})->simplePaginate(5);
this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?
The pagination methods should be called on queries instead of collection.
You could try:
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
The problem was solved. I was create custom paginator via this example:
https://stackoverflow.com/a/30014621/6405083
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 15; // Number of results per page
$count = Project::count(); // Get the total number of entries you'll be paging through
// Get the actual items
$projects = Project::orderBy('created_at', 'desc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
return $project->created_at->format('Y-m-d');
});
$data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
simplePaginate Method is exist in the path below:
Illuminate\Database\Eloquent\Builder.php::simplePaginate()

How to paginate and sort results in Laravel?

I need to paginate the results and sort them using sortBy(), without losing the pagination links. I also need to use a resource to return the results.
$sorted = Model::paginate(10)->sortBy('name');
$results = \App\Http\Resources\MyResource::collection($sorted);
Doing this breaks the pagination links (I get only the data part).
$paginated = Model::paginate(10);
$results = \App\Http\Resources\MyResource::collection($paginated);
return $results->sortBy('name');
This also doesn't work.
Any ideas?
Using the getCollection() and setCollection() method in the paginator class, You can update the pagination result without losing the meta data.
$result = Post::orderBy('another_key')->paginate();
$sortedResult = $result->getCollection()->sortBy('key_name')->values();
$result->setCollection($sortedResult);
return $result;
I think you can sort the results first, and then paginate
$sorted = Model::orderBy('name')->paginate(10);
I've solved the problem with this solution:
$sorted = Model::get()
->sortBy('example_function') //appended attribute
->pluck('id')
->toArray();
$orderedIds = implode(',', $sorted);
$result = DB::table('model')
->orderByRaw(\DB::raw("FIELD(id, ".$orderedIds." )"))
->paginate(10);
I've appended example_function attribute to the model, to be used by sortBy. With this solution I was able to use orderBy to order by an appended attribute of the model. And also I was able to use pagination.

Laravel: How to update pivot tables withou using first

Im new in Laravel. I want to update my leaves pivot table. I am trying with below code but it only updates the single row i have multiple rows in db with same leave_id and i want to update all this where leave_id = xyz
I have following function in my model Leave:
public function relLeave(){
return $this->belongsToMany(User::class)->withPivot('days');
}
LeaveController:
public function saveUpdate(Request $request)
{
$leave = Leave::find($request->id);
$msg = $leave->relLeave()->Where('leave_id', $request->id)->get()->first();
$msg->pivot->days = $request->days;
$msg->pivot->save();
}
I followed #option's instruction and it works for me i removed the first();
below is my updated code.
$msg = $leave->relLeave()->Where('leave_id', $request->id)->get();
foreach($msg as $msgs)
{
$msgs->pivot->days = $request->days;
$msgs->pivot->save();
}
you can update extra fields in pivot table when updating relationship
$leave->relLeave()->sync([$request['id'] => ['days' => $request['days']]]);
You can use Query Builder for that if it's an option:
DB::table('leave_user')->where('leave_id', $request->id)->update(['days' => $request->days]);
This is just one DB query and it's pretty simple one.
If you want Eloquent solution, use updateExistingPivot() in a loop:
$leave = Leave::find($request->id);
$usersIds = $leave->relLeave()->pluck('id')->toArray();
foreach ($usersIds as $userId) {
$leave->relLeave()->updateExistingPivot($userId, ['days' => $request->days]);
}

Resources