Laravel 5.2 Create function - laravel

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.

Related

blade - foreach $loop->iteration

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

Find Data Using Laravel Framework

I want match data from "jobTable" based on job id then i got 5 data within this 5 data i have userId i want to show data from "userTable" based on userID. Then i will catch it on variable and i want to show it on my view then i will show it using loop.
If i do this below code it shows all data from my userTable not show based on matched JobID base UserId Details.
public function applyUser($jobId){
$applyUsers=ApplyInfo::where('job_id', $jobId)->get();
//5 rows found, with in this 5 rows everybody has userId I want to show data from user table based on this found userId and pass value a variable then i will loop it on view page.
foreach ($applyUsers as $applyUser){
$applyUsersDtials=Employee::find($applyUser->user_id)->get();
}
return view('front.user.apply-user-details', ['applyUsersDtials'=>$applyUsersDtials]);
}
//when i do that that time show all data based on my user table not show based on my JobId
First of all in your code $applyUsersDtials is a variable it should be an array. Next when you need to find a single row you just need to use find(). Try this-
public function applyUser($jobId){
$applyUsers = ApplyInfo::where('job_id', $jobId)->get();
$applyUsersDtials = [];
foreach ($applyUsers as $applyUser){
$applyUsersDtials[] = Employee::find($applyUser->user_id);
}
return view('front.user.apply-user-details',
['applyUsersDtials' => $applyUsersDtials]);
}

Eloquent insert or update query

I have a settings table which i am trying to update. My table is empty and i need to insert some data into it.
I am using eloquent to insert
$s = new Settings;
$s->language = request('language');
$s->sitename = request('sitename');
$s->user_id = Auth::id();
$s->save();
return redirect('settings');
I have come across this function
$se = Settings::findOrNew($id); // if exist then update else insert
The findOrNew requires me to know the id before i can save.
How can insert or update without knowing the id(which may not even exist in the first place).
Well in that cause you can use firstOrNew
since you said your basis is you wanted to check if that user_id already exist in table then you use it as condition instead of id
first -> you use firstOrNew
this function do is
check if condition exist it then if it exist it will just return the first existing data
if not just insert a new data and return the new insert data
$s = User::firstOrNew(array('user_id' => Auth::id()));
Then -> after that you can now use that object and do what you wanted to do on it
$s->language = request('language');
$s->sitename = request('sitename');
$s->save();

custom reason message for magento reward points

How to add a custom reason message for a reward action ?
I have created :
$customerId = 1303177;
$points = 10;
$customer = Mage::getModel('customer/customer')->load($customerId);
$reward = Mage::getModel('enterprise_reward/reward')
->setCustomer($customer)
->setWebsiteId(2)
->loadByCustomer();
$reward->setPointsDelta($points)
->setAction(Enterprise_Reward_Model_Reward::REWARD_ACTION_ADMIN)
->setComment('Added programmatically')
->updateRewardPoints();
i like to add something like
$reward->setReason('bonus point');
that would be visible in the reason column of the customer reward history ( back office )
If reason column already exists in the Rewards database table, then all you need is to use
$reward->setReason('bonus point');
$reward->save();
to save the values.
But if reason column doesn't exist then first create a new column reason in the database and then use the above code to save the values in that field.

laravel4 update additional columns in pivot table

I'm trying to update additional column data in a pivot table in a many to many relationship.
I have two tables - reservation and resource linked with a pivot table. I can attach and am working with the model. However I'm struggling to update one of the additional columns in the pivot table.
I have an object: '$reservation' From that object I created another object $resources using:
$resources = $reservation->resource()->get();
I'm then iterating through $resources using a foreach loop as follows
foreach($resources as $resource ) {...}
I then want to update a column called gcal_id and am using the following:
$resource->pivot->gcal_id = "TEST";
$resource->save();
If I var_dump the model I can see the property exists to the correct value but in the database itself the entry is not being updated - so the save is not working
I have the columns listed in both sides of the relationship with this:
->withPivot('start', 'end', 'quantity', 'product_id','gcal_id')
Given I have the resource object how can I update a column correctly in the pivot table and save to database?
Thanks
After that you set the attribute on the pivot:
$resource->pivot->gcal_id = "TEST";
You seem to save the resource and not the pivot:
$resource->save();
If you want the pivot to be saved, saving the resource is not enough. Call save on the pivot instead:
$resource->pivot->gcal_id = "TEST";
$resource->pivot->save();
An alternative instead of save method, is the method Illuminate\Database\Eloquent\Relations\BelongsToMany\updateExistingPivot()
$reservation->resource()->updateExistingPivot($resource_id, ['gcal_id' => 'TEST']);
Or
$reservation->resource()->updateExistingPivot([1, 4, 5, 6], ['gcal_id' => 'TEST']);
This work for me in Laravel 4.2

Resources