blade - foreach $loop->iteration - laravel

I've problem with some loops.
I have 2 tables Terms [id, caption, ...] and apps [id, term_id, name, ...]
And in my view i want print all apps orderred by term_id and then by name. But i want 1 table for each term_id used in apps. and i want 1st col with correct $loop->iteration (i mean each table first row start with 1, not with +1 from previous table last row)
in controller I've passing 2 variables to my views (i have different views for each appState_id value)
$app = Application::where('ApplicationState_id',3)->get();
$term = Terms::all();
return view('admin.index')->with('terms', $term)
->with('apps', $app);
in view i used foreach inside foreach / i rebuild it little bit
foreach terms as term
foreach apps as app
if $loop->first {<table><thead> ... table caption row ...}
checking if app->term_id = term->id
$loop->iteration, and some other stuff
if $loop->last {</table>}
endforeach
endforeach
but I want it improve little bit:
it write table's first/caption/ row for all term even there is no record in app table
$loop->iteration is combined per all records
i want it per each table separately-i dont know can i do it
How can i pass all data from controller to be able print them seprately to corespond table?
Is there a better way how to do this? thanks for advice/hint
---edited litle bit shortened
Application.php
class Application extends Model
{
protected $fillable = [
'nickname',
'comment',
'term_id',
'applicationstate_id',
];
public function term()
{
return $this->belongsTo('App\Term', 'Term_id');
}
}
Term.php - this model/table is meantime filled by me, but I want to change in future that user can add another terms of events
class Term extends Model
{
public function applications()
{
return $this->hasMany('App\Application');
}
}
I had idea that i can in controller:
check how many unique term_id is in Application table {n}
loop 1... {n}
inside loop read data from DB for each query/each term_id and add result to an array
send this array of results to view
and then try print it as {n} tables for each term_id
is this good idea how to solve this, or there is something much better?
table applications
data from applications table/few records/
ideal output on page
ideal output scheme

Can you paste two models in your application
Edit
In your application class change the foreign key for trem
public function term() {
return $this->belongsTo('App\Term', 'term_id');
}
In your controller
$app = Application::with('term')->where('applicationstate_id',3)->get();
return view('admin.index')->with('apps', $app);
In your admin/index.blade.php
#foreach($apps as $item )
$item->trem->your attributes trem
$item->nickname
#endforech

I did it this way:
check how many unique term_id is in Application table {n}
loop 1... {n}
inside loop read data from DB for each query/each term_id and add result to an array
then I send this array of results to view

Related

Using Laravel Eloquent to count how many times something exists in an efficient manner

I have a table called rentals, within each row are columns state,city,zipcode which all house ids to another table with that info. There are about 3400 rentals. I am pulling each column to display the states,city and zipcode distinctly. I need to show how many rentals are in each one. I am doing this now via ajax, the person starts typing in what they want to see and it auto completes it with the count, but its slow because of the way im doing it.
$rentals_count = Rentals::where('published',1)->get();
foreach($states as $state) {
echo $state.”-“.$rentals_count->where(‘state’,$state->id)->count();
}
Above is roughly what im doing with pieces removed because they are not related to this question. Is there a better way to do this? It lags a bit so the auto complete seems broken to a new user.
Have you considered Eager loading your eloquent query? Eager loading is used to reduce query operations. When querying, you may specify which relationships should be eager loaded using the with method:
$rental_counts = Rentals::where('published',1)->with('your_relation')->get();
You can read more about that in Laravel Documentation
$rentals = Rentals::wherePublished(true)->withCount('state')->get();
When you loop through $rentals, the result will be in $rental->state_count
Setup a relation 'state' on rentals then call it like this
$rentals_count = Rentals::where('published',1)->with('state')->get()->groupBy('state');
$rentals_count->map(function($v, $k){
echo $v[0]->state->name .' - '. $v->count();
});
Meanwhile in Rentals Model
public function state(){
return $this->hasOne(State::class, 'state'); //state being your foreign key on rentals table. The primary key has to be id on your states table
}

how to make relation between table and array of ids from another table laravel

i have 2 tables, stores and products
stores table has field called products_ids
in this case i am saving the products in the stores by their ids in products_ids field as an array like this [1,2,3,4,5] i know it's not good practice to do it like this but this is the situation.
how can i make a relation in the model to achieve thing like this
Store::with('products')->get();
thanks
I don't know if this would work for you, but try it anyway:
in your Store model add the following:
public function products ()
{
return Product::whereIn('id', $this->products_ids)->get();
}

Laravel 5.2 Create function

i've been building a basic laravel CRUD system, with that i've made a basic create funciton but i want to make it so that if a record already exists in the database and u create the same record again that the Integer u put in the create form add's up by the already existing record example: u have a stock system with a product that has the ammount of 50, and u create the same product with the ammount of 40, and that the 40 add's up with the 50 so that in the database it will say 90. im not entirely sure how to do so.
This is the store function i've made for my application:
public function store(Request $request)
{
// Aantal = ammount (int)
//Producten_Id = foreign_key from the Producten database table
//Locaties_Id = foreign_key from the locaties database table
Voorraad::Create($request->only(['aantal', 'Producten_Id', 'Locaties_Id']));
//var_dump($request);
return redirect(Route('voorraad.index'));
}
if u need more information just let me know and i'll add it to the question
Assuming that you set up default value for this field in database structure, its as simple as:
$voorraad = Voorraad::firstOrCreate($request->only(['Producten_Id', 'Locaties_Id']);
$voorraad->increment('aantal', $request->aantal);
If you want to set default amount for new products in the controller do this instead:
$voorraad = Voorraad::firstOrCreate($request->only(['Producten_Id', 'Locaties_Id']);
if (! $voorraad->aantal) {
$voorraad->aantal = 123; // default
}
else {
$voorraad->aantal += $request->aantal;
}
$voorraad->save();
Generally speaking firstOrCreate method fetches from database record with passed attributes if it exists already or otherwise creates it. See in Laravel docs.
If you have any questions just ask in comments, I'll be happy to explain.

Join query in laravel with data manipulation send to view

I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit

Updating a pivot table in Eloquent

I've got a many to many relationship between a student and an institution_contact.
students should only ever have two institution_contacts and I have an attribute on the pivot table named type to be set as 1 or 2.
So, my pivot table looks like this:
institution_contact_student: id, institution_contact_id, student_id, type
I've run into difficulty in deciding how to approach the issue of adding/updating the pivot table. Let's say I have 100 students and I want to assign them a contact with the type of 1.
My current solution is to delete the contact then add it:
$students = Student::all(); // the 100 students
$contactId = InstitutionContact::first()->id; // the contact
foreach ($students as $student) {
// remove existing contact
$student
->institutionContacts()
->newPivotStatement()
->where('type', 1)
->delete();
// add new contact
$student
->institutionContacts()
->attach([$contactId => ['type' => 1]]);
}
However, I'm thinking that this is going to hit the database twice for each student, right? So would I be better off creating a model for the pivot table and removing all entries that matched the student id and the type then simply adding the new ones? Or would creating a model for the pivot table be considered bad practice and is there a better way of accomplishing this that I've missed?
Please note the reason I'm not using sync is because I'm relying on the type attribute to maintain only two contacts per student. I'm not aware of a way to modify an existing pivot without causing issues to my two contacts per student requirement.
Edit:
Instead of creating a model I could run the following code to perform the delete using DB.
DB::table('institution_contact_student') // the pivot table
->whereIn('student_id', $studentIds)
->where('type', 1)
->delete();
If I have understood your question correctly then you can use the updateExistingPivot method for updating your pivot table.But first of course you have to define the pivot in your relationship. For instance,
public function institutionContacts(){
return $this->belongsToMany('institutionContact')->withPivot('type');
}
after this, all you have to do is use the following code:
$student
->institutionContacts()
->updateExistingPivot($contactId, ["type" => 1]);
Hope this helps.

Resources