updateOrCreate() updating database using index - laravel

I have a submit and update function for my form and in that form, the user can choose to add an additional row of inputs. These inputs will be saved in a new row, basically, one user can have several rows in the database. I have a problem with the update function, where if the user originally has two rows answered, in the update function if they still fill in two rows, both of the rows in the database will be updated, however, only the first row is getting updated. I tried accessing the key for the arrays and updating based on the array keys but it doesn't work.
Here is my whole controller:
<?php
namespace App\Http\Livewire;
use Illuminate\Support\Facades\Validator;
use App\Http\Livewire\Field;
use Illuminate\Http\Request;
use App\Helpers\Constant;
use App\Models\User;
use App\Models\Application;
use App\Models\Model1;
use App\Models\Model2;
use App\Models\Model3;
use App\Models\Model4;
use Livewire\Component;
use DB;
class ModelComponent extends Component
{
public $i = 1;
public $updateMode = false;
public $model2Rows = [];
public $model4Rows = [];
public $showDiv1 = false;
public $showDiv2 = false;
public $showDiv3 = false;
public $showDiv4 = false;
public $m1_field;
public $m1_field2;
public $m2_field;
public $m2_field2;
public $m3_field;
public $m3_field2;
public $m4_field;
public $m4_field2;
public function openDiv($divNum)
{
if($divNum == 1) {
$this->showDiv1 =! $this->showDiv1;
} else if($divNum == 2) {
$this->showDiv2 =! $this->showDiv2;
} else if($divNum == 3) {
$this->showDiv3 =! $this->showDiv3;
} else if($divNum == 4) {
$this->showDiv4 =! $this->showDiv4;
}
}
public function addMoreModel2Rows($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->model2Rows , $i);
}
public function addMoreModel4Rows($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->model4Rows , $i);
}
public function removeModel2Rows($i)
{
unset($this->model2Rows[$i]);
}
public function removeModel4Rows($i)
{
unset($this->model4Rows[$i]);
}
public function submit()
{
$user = auth()->user();
$application = Application::create([
'app_type_id' => 1,
'approval_status_id' => 1
]);
$application->users()->save($user);
$rules = [];
$validatedData = [];
if($this->showDiv1){
$rules = array_merge($rules, [
'm1_field' => 'required',
'm1_field2' => 'required',
]);
}
if($this->showDiv2){
$rules = array_merge($rules, [
'm2_field.0' => 'required',
'm2_field2.0' => 'required',
'm2_field.*' => 'required',
'm2_field2.*' => 'required',
]);
}
if($this->showDiv3){
$rules = array_merge($rules, [
'm3_field' => 'required',
'm3_field2' => 'required',
]);
}
if($this->showDiv4){
$rules = array_merge($rules, [
'm4_field.0' => 'required',
'm4_field2.0' => 'required',
'm4_field.*' => 'required',
'm4_field2.*' => 'required',
]);
}
$validatedData = $this->validate($rules);
if($this->showDiv1){
Model1::create([
'user_id' => $user->user_id,
'm1_field' => $validatedData['m1_field'],
'm1_field2' => $validatedData['m1_field2'],
]);
}
if($this->showDiv2){
foreach ($this->m2_field as $key => $value){
Model2::create([
'user_id' => $user->user_id,
'm2_field' => $validatedData['m2_field'][$key],
'm2_field2' => sanitize_money($validatedData['m2_field2'][$key]),
]);
}
}
if($this->showDiv3){
Model3::create([
'user_id' => $user->user_id,
'm3_field' => $validatedData['m3_field'],
'm3_field2' => $validatedData['m3_field2'],
]);
}
if($this->showDiv4){
foreach ($this->m4_field as $key => $value){
Model4::create([
'user_id' => $user->user_id,
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
}
}
$user->save();
alert('success','Your details are saved.');
return redirect()->route('website.landing');
}
public function update()
{
// get user info in session
$user = auth()->user();
$i = 0;
$model2 = Model2::where('user_id', $user->user_id)->get();
$model4 = Model4::where('user_id', $user->user_id)->get();
$rules = [];
$validatedData = [];
if($this->showDiv1){
$rules = array_merge($rules, [
'm1_field' => 'required',
'm1_field2' => 'required',
]);
}
if($this->showDiv2){
$rules = array_merge($rules, [
'm2_field.0' => 'required',
'm2_field2.0' => 'required',
'm2_field.*' => 'required',
'm2_field2.*' => 'required',
]);
}
if($this->showDiv3){
$rules = array_merge($rules, [
'm3_field' => 'required',
'm3_field2' => 'required',
]);
}
if($this->showDiv4){
$rules = array_merge($rules, [
'm4_field.0' => 'required',
'm4_field2.0' => 'required',
'm4_field.*' => 'required',
'm4_field2.*' => 'required',
]);
}
$validatedData = $this->validate($rules);
if($this->showDiv1){
EmploymentDetail::updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm1_field' => $validatedData['m1_field'],
'm1_field2' => $validatedData['m1_field2'],
]);
}
if($this->showDiv2){
foreach ($this->m2_field as $key => $value){
$partTime[$key]->updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm2_field' => $validatedData['m2_field'][$key],
'm2_field2' => sanitize_money($validatedData['m2_field2'][$key]),
]);
}
}
if($this->showDiv3){
Model3::updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm3_field' => $validatedData['m3_field'],
'm3_field2' => $validatedData['m3_field2'],
]);
}
if($this->showDiv4){
foreach ($this->m4_field as $key => $value){
if(!empty($model4[$i])){
$model4[$i]->updateOrCreate(
[
'user_id' => $user->user_id,
],
[
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
} else {
Model4::create([
'user_id' => $user->user_id,
'm4_field' => $validatedData['m4_field'][$key],
'm4_field2' => sanitize_money($validatedData['m4_field2'][$key]),
]);
}
}
}
alert('success','Your income are updated.');
return redirect()->route('borrower.joint_declaration');
}
public function render()
{
$income_informations = DB::table('income_informations')->get();
$showDiv1 = $this->showDiv1;
$showDiv2 = $this->showDiv2;
$showDiv3 = $this->showDiv3;
$showDiv4 = $this->showDiv4;
return view('livewire.model-component',
[
'income_informations' => $income_informations,
'showDiv1'=>$showDiv1,
'showDiv2'=>$showDiv2,
'showDiv3'=>$showDiv3,
'showDiv4'=>$showDiv4,
]);
}
}
I created a variable to store the arrays because I realized that if I simply use the model name and then do updateOrCreate() it will probably only update the first one. But the result of that update function is that it updates the first row in the database, then creates a new row for the additional row, but I want it to update the other rows in the database instead.
For more context, I followed through this tutorial for the adding input fields and saving function. Now I have trouble trying to do the update function.

Related

How to get from request->value one value at a time inside foreach loop

Hello i have this code in laravel controller and i get an error for a single value:
public function store(Request $request)
{
$values = [];
$request->validate([
'order_number' => 'required',
'client_id' => 'required|exists:clients,id',
'description' => 'required',
'products' => 'required|exists:products,id',
'amount' => 'required',
]);
$order = Order::create($request->all());
foreach ($request->products as $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product,
'amount' => $request->amount,
];
$amount = Product::find($product);
$total_value = $request->amount + $amount->amount; //the error happens here
$amount->update(['amount' => $total_value]);
}
$order->products()->attach($values);
return redirect('/')->with('msg', 'Order Saved successfully!');
}
All the values come except the $request->amount that comes as array and not as a single value in a row. This is the error i get:
Unsupported operand types: array + string
This is the product model:
protected $fillable = [
'name',
'price',
'amount',
];
public function orders()
{
return $this->belongsToMany(Order::class);
}
And this is dd($request->amount);
Assuming that $request->amount is directly related to $request->products with the index then you would either need to combine products and amount before you send the request or iterate over products with the index.
foreach ($request->products as $index => $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product,
'amount' => $request->amount[$index], //Reference via index
];
$amount = Product::find($product);
$total_value = $request->amount[$index] + $amount->amount; //Also here
}
}

Laravel - local.ERROR: Error: Call to undefined function App\Imports\create() in Excel Import

I am using Laravel-8 and Maatwebsite-3.1 package for excel upload:
I have this Excel sheet (The data is more thank that):
imports:
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\DefaultValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Validators\Failure;
use Throwable;
class EmployeeImport extends DefaultValueBinder implements OnEachRow, WithStartRow, SkipsOnError, WithValidation, SkipsOnFailure, WithEvents, WithCustomValueBinder
{
// set the preferred date format
private $date_format = 'Y-m-d';
// set the columns to be formatted as
private $date_columns = ['E'];
use Importable, SkipsErrors, SkipsFailures;
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
if($rowIndex >= 1000)
return; // Not more than 1000 rows at a time
$row = $row->toArray();
$employee_data = [
'first_name' => $row[0],
'other_name' => $row[1] ?? '',
'last_name' => $row[2],
'email' => preg_replace('/\s+/', '', strtolower($row[3])),
'dob' => $this->transformDate($row[4]),
];
$employee = create(Employee::class, $employee_data);
if (User::where('email', '=', $employee->email)->exists()) {
$user = User::update([
'first_name' => $employee->first_name,
'last_name' => $employee->last_name,
'active' => 1,
]);
}else{
$user = User::create([
'email' => $employee->email,
'first_name' => $employee->first_name,
'last_name' => $employee->last_name,
'active' => 1,
]);
}
$employee->update([
'user_id' => $user->id,
]);
}
public function startRow(): int
{
return 2;
}
public function customValidationAttributes()
{
return [
'0' => 'First Name',
'1' => 'Other Name',
'2' => 'Last Name',
'3' => 'Email',
'4' => 'Date of Birth',
];
}
public function rules(): array
{
return [
'*.0' => [
'required',
'string',
'max:50'
],
'*.1' => [
'nullable',
'string',
'max:50'
],
'*.2' => [
'required',
'string',
'max:50'
],
'*.3' => [
'required',
'email',
'max:100',
Rule::unique('employees', 'email')->where(function ($query) {
return $query->where('company_id', Auth::user()->company_id);
})
],
'*.4' => [
'required',
'date_format:Y-m-d',
'before:' . Carbon::now()->subYears(18)->format('Y-m-d')
],
];
}
public function chunkSize(): int
{
return 1000;
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
}
Controller:
public function importEmployee(Request $request)
{
$validator = Validator::make($request->all(), [
'document' => 'file|mimes:xls,xlsx|max:5000',
]);
if ($request->hasFile('document'))
{
if($validator->passes()) {
$import = new EmployeeImport;
$file = $request->file('document');
$file->move(public_path('storage/employee_imports'), $file->getClientOriginalName());
Excel::import($import, public_path('storage/employee_imports/' . $file->getClientOriginalName() ));
return $this->success('Employees Imported.', [
'file' => $file
]);
}else{
return $this->error($validator->errors(), 422);
}
}
}
When I submitted, I got this error:
[2021-08-19 09:33:40] local.ERROR: Error: Call to undefined function
App\Imports\create() in
C:\xampp\htdocs\myapp\app\Imports\EmployeeImport.php:98
Stack trace:
#0 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Sheet.php(301):
App\Imports\EmployeeImport->onRow(Array)
#1 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Reader.php(114): Maatwebsite\Excel\Sheet->import(Object(App\Imports\EmployeeImport), 2)
#2
C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Concerns\ManagesTransactions.php(29): Maatwebsite\Excel\Reader->Maatwebsite\Excel{closure}(Object(Illuminate\Database\MySqlConnection))
This is the line 98:
$employee = create(Employee::class, $employee_data);
How do I resolve this?
Thanks
Change this line
$employee = create(Employee::class, $employee_data);
to
$employee = Employee::create($employee_data);
create is not a function alone. Check this link
https://laravel.com/docs/8.x/eloquent#inserting-and-updating-models

Laravel - Maatwebsite Excel import stored in storage only but not in DB

I am importing Excel File using Laravel-8 endpoints and Maatwebsite-3.1 package.
The way I did it is that, the Uploaded Excel file will first get to the storage (storage/file_imports/student_imports). Then Laravel pickes it up from there, stores it into the DB table through StudentImport using Maatwebsites.
StudentImport:
<?php
namespace App\Imports;
use App\Models\User;
use App\Models\Student;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Validators\Failure;
use Throwable;
class StudentImport implements
ToModel,
WithValidation,
WithHeadingRow,
SkipsOnError,
SkipsOnFailure,
WithBatchInserts
{
protected $companyId;
public function __construct()
{
$this->companyId = Auth::user()->company_id;
}
use Importable, SkipsErrors, SkipsFailures;
public function model(array $row)
{
$student_data = [
'first_name' => $row[0],
'other_name' => $row[1] ?? '',
'last_name' => $row[2],
'email' => preg_replace('/\s+/', '', strtolower($row[3])),
'gender' => $row[4],
'nationality_id' => $this->getNationality() ?? '',
'school_id' => Auth::user()->school_id,
];
$student = Student::create($student_data);
if (User::where('email', '=', $student->email)->exists()) {
$user = User::update([
'first_name' => $student->first_name,
'other_name' => $student->other_name,
'last_name' => $student->last_name,
'complete_profile' => 1,
'active' => 1,
'user_type' => 'Driver',
'company_id' => Auth::user()->company_id,
'updated_at' => date("Y-m-d H:i:s"),
'updated_by' => Auth::user()->id,
]);
}else{
$user = User::create([
'email' => $student->email,
'username' => strtok($row[3], '#'),
'password' => bcrypt("123456"),
'first_name' => $student->first_name,
'other_name' => $student->other_name,
'last_name' => $student->last_name,
'activation_token' => str_random(10),
]);
}
}
public function headingRow(): int
{
return 1;
}
public function getRowCount(): int
{
return $this->rows;
}
public function customValidationAttributes()
{
return [
'0' => 'First Name',
'1' => 'Other Name',
'2' => 'Last Name',
'3' => 'Email',
'4' => 'Gender',
];
}
public function rules(): array
{
return [
'*.0' => [
'required',
'string',
'max:50'
],
'*.1' => [
'nullable',
'string',
'max:50'
],
'*.2' => [
'required',
'string',
'max:50'
],
'*.3' => [
'required',
'email',
'max:100',
Rule::unique('studentss')->where(function ($query) {
return $query->where('school_id', Auth::user()->school_id);
})
],
'*.4' => [
'required',
'string',
'max:20'
],
];
}
public function batchSize(): int
{
return 1000;
}
public function chunkSize(): int
{
return 1000;
}
public function onFailure(Failure ...$failures)
{
// Handle the failures how you'd like.
}
public function customValidationMessages()
{
return [
'1.in' => 'Custom message for :attribute.',
'nim.unique' => 'Custom message',
];
}
}
Controller:
public function importStudent(Request $request)
{
try {
$user = Auth::user()->id;
$validator = Validator::make($request->all(), [
'document' => 'file|mimes:xlsx|max:10000',
]);
if($validator->fails()) {
return $this->error($validator->errors(), 401);
} else {
$check = User::where('id', $user)->pluck('id');
if($check[0] !== null || $check[0] !== undefined) {
$file = $request->file('document');
$file->move(public_path('storage/file_imports/student_imports'), $file->getClientOriginalName());
Excel::import(new StudentImport, public_path('storage/file_imports/student_imports/' . $file->getClientOriginalName() ));
return $this->success('Students Successfully Imported.', [
'file' => $file
]);
} else {
return $this->error('Not allowed', 401);
}
}
} catch(\Exception $e) {
return $this->error($e->getMessage());
}
}
As I stated earlier it will first store the Excel file into:
storage/file_imports/student_imports
Then pick it from there and store in the DB.
This code is in the controller above.
The file is store in the
public/storage/file_imports/student_imports
as expected, but nothing is found in the DB. Yes it displays Success with no error.
What could be the problem and how do I resolve it?
Thanks
model method in your StudentImport class must return new instance of Eloquent model.
You shouldn't make create or update method call through your model in here.
Maatwebsite-Excel manage your insert process with own manager. Check source code.
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelImporter.php#L74
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelImporter.php#L92
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelManager.php#L45
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/src/Imports/ModelManager.php#L64

Error column not found, but I did not declare the column?

I'm inserting a record to a polymorphic imageable table, however it says column thread_id not found. I have not declared this thread_id column and I don't know where it's pulling it from. Here is the code it's trying to run.
protected static function bootRecordImage()
{
if (auth()->guest()) return;
foreach (static::getMethodToRecord() as $event) {
static::$event(function ($model) use ($event) {
$body = request()->body;
preg_match_all('/<img .*?(?=src)src=\"([^\"]+)\"/si', $body, $matches);
$images = $matches[1];
if($event == 'created') {
foreach ($images as $image) {
$model->images()->create([
'user_id' => auth()->id(),
'imageable_id' => $model->id,
'imageable_type' => get_class($model),
'path' => $image
]);
}
}
if($event == 'deleting') {
foreach ($images as $image) {
$model->images()->delete([
'user_id' => auth()->id(),
'imageable_id' => $model->id,
'imageable_type' => get_class($model),
'path' => $image
]);
if (File::exists(public_path($image))) {
File::delete(public_path($image));
}
}
}
});
}
}
My store method:
public function store(Request $request, Channel $channel, Spam $spam)
{
if (!auth()->user()) {
return back()->withInput()->with('flash', 'Sorry! You must be logged in to perform this action.');
}
if (!auth()->user()->confirmed) {
return back()->withInput()->with('flash', 'Sorry! You must first confirm your email address.');
}
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'channel_id' => 'required|exists:channels,id',
'g-recaptcha-response' => 'required'
// yes it's required, but it also needs to exist on the channels model, specifically on the id
]);
$response = Zttp::asFormParams()->post('https://www.google.com/recaptcha/api/siteverify', [
'secret' => config('services.recaptcha.secret'),
'response' => $request->input('g-recaptcha-response'),
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
// dd($response->json());
if (! $response->json()['success']) {
throw new \Exception('Recaptcha failed');
}
$spam->detect(request('title'));
$spam->detect(request('body'));
$thread = Thread::create([
'user_id' => auth()->id(),
'channel_id' => request('channel_id'),
'title' => request('title'),
'body' => request('body'),
//'slug' => str_slug(request('title'))
]);
return redirect('/forums/' . $thread->channel->slug . '/' . $thread->slug);
}
As you can see, no where is a thread_id mentioned, yet in the error it looks like it's trying to insert into a thread_id column that I've never declared.
Thanks for reading.
I put the polymorphic relation in the model and the trait. Remove it from the Model and you're good to go.

creating default object from empty value in laravel 5

I'm trying to make two functions in controller that have post action and that are in the same page.
My Controller
public function store(Request $request)
{
$status = DB::table('analytics')->where('dienstleistung', '!=', '')->get();
//Save data
$rules = [
'site_id' => 'required',
'dienstleistung' => 'required',
'objekt' => 'required',
'zimmer' => 'required',
'vorname' => 'required',
'name' => 'required',
'strasse' => 'required',
'ort' => 'required',
'plz' => 'required',
'tel' => 'required',
'email' => 'required|email',
'reinigungstermin' => 'required',
'gekommen' => 'required',
'message' => 'required',
'status' => 'required',
'answer' => 'required',
'notiz' => 'required',
'userId' => 'required',
];
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::to('anfrage')
->withErrors($validator)
->withInput();
}
else {
$anfrage = new Analytic();
$anfrage->site_id = Input::get('site_id');
$anfrage->dienstleistung = Input::get('dienstleistung');
$anfrage->objekt = Input::get('objekt');
$anfrage->zimmer = Input::get('zimmer');
$anfrage->vorname = Input::get('vorname');
$anfrage->name = Input::get('name');
$anfrage->strasse = Input::get('strasse');
$anfrage->ort = Input::get('ort');
$anfrage->plz = Input::get('plz');
$anfrage->tel = Input::get('tel');
$anfrage->email = Input::get('email');
$anfrage->reinigungstermin = Input::get('reinigungstermin');
$anfrage->gekommen = Input::get('gekommen');
$anfrage->message = Input::get('message');
$anfrage->status = Input::get('status');
$anfrage->answer = Input::get('answer');
$anfrage->notiz = Input::get('notiz');
$anfrage->userId = Input::get('userId');
try {
$anfrage->save();
flash()->success(trans('app.success'));
return Redirect::to('anfrage');
} catch (\Exception $e) {
Log::writeException($e);
return Redirect::to('anfrage')
->withErrors($e->getMessage())
->withInput();
}
}
}
public function editItem(Request $request) {
$anfrages = Analytic::find($request['id'] );
$anfrages->status = $request->status;
$anfrages->answer = $request->answer;
$anfrages->notiz = $request->notiz;
$anfrages->save();
return response ()->json( $anfrages );
}
My route:
Route::post('anfrage', 'AnfrageController#store');
Route::post ( 'anfrage', 'AnfrageController#editItem' );
EditItem function is OK, it makes changes when I want to edit data, but when I want to store data, message being displayed is:
creating default object from empty value
So, I need to leave active only one of these function, both are not working.

Resources