Call to a member function extension() on null when updating my post - php

Please I have an issue with my code. whenever I want to update my post it always says my files are empty although I have an old file. Please can you help me to fix it? Thanks in advance.
This my controller
public function update(Request $request, $id)
{
$allowedOptions = Constants::ACTIVE . ",". Constants::INACTIVE;
$allowedTypes = Constants::MUSIC;
$data = $request->validate([
'category_id' => "required|string",
'name' => 'required|string',
'content_desccription' => 'required:string',
"type" => "required|string|in:$allowedTypes",
"meta_title" => "required|string",
"meta_keywords" => "required|string",
"meta_description" => "required|string",
"is_sponsored" => "required|string|in:$allowedOptions",
"is_top_story" => "required|string|in:$allowedOptions",
"is_featured" => "required|string|in:$allowedOptions",
"is_published" => "required|string|in:$allowedOptions",
"can_comment" => "required|string|in:$allowedOptions",
]);
if (!empty([
$image_path = MediaFilesHelper::saveFromRequest($request->cover_image, "postImages", $request),
$music_path = MediaFilesHelper::saveFromRequest($request->cover_music, "postMusic", $request),
]));
$data['cover_image'] = $image_path;
$data['cover_music'] = $music_path;
$post = Post::where('id', $id)->update($data);
return redirect()->route('admin.post.index')->with('success_meassage', 'Post updated successfully');
}
This is the code handly the file
public static function saveFromRequest($file , $path , Request $request)
{
$file_name = Str::slug($request->name, '-').".".$file->extension();
$file->move(public_path($path) , $file_name);
return $path."/".$file_name;
}

I have changed your file condition now try I hope it work for you now.
public function update(Request $request, $id)
{
$allowedOptions = Constants::ACTIVE . ",". Constants::INACTIVE;
$allowedTypes = Constants::MUSIC;
$data = $request->validate([
'category_id' => "required|string",
'name' => 'required|string',
'content_desccription' => 'required:string',
"type" => "required|string|in:$allowedTypes",
"meta_title" => "required|string",
"meta_keywords" => "required|string",
"meta_description" => "required|string",
"is_sponsored" => "required|string|in:$allowedOptions",
"is_top_story" => "required|string|in:$allowedOptions",
"is_featured" => "required|string|in:$allowedOptions",
"is_published" => "required|string|in:$allowedOptions",
"can_comment" => "required|string|in:$allowedOptions",
]);
if ($request->file('cover_image')) {
$image_path = MediaFilesHelper::saveFromRequest($request->cover_image, "postImages", $request);
$data['cover_image'] = $image_path;
}
if ($request->file('cover_music')) {
$music_path = MediaFilesHelper::saveFromRequest($request->cover_music, "postMusic", $request);
$data['cover_music'] = $music_path;
}
$post = Post::where('id', $id)->update($data);
return redirect()->route('admin.post.index')->with('success_meassage', 'Post updated successfully');
}

Related

enter a view inserts an empty record

i have a problem, every time I enter or refresh a page it inserts a new record
Controller:
public function cobrar(Request $request,$id){
$data = [
'category_name' => 'datatable',
'page_name' => 'custom',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$cliente = \App\Models\Eventos::first();
$cobros = \App\Models\Cobros::where('turno_id', $request->id)->first();
$evento = \App\Models\Eventos::where('id' , $id)->with('servicio')->first();
$servicio = \App\Models\Servicios::where('id', $evento->servicio_id)->first();
$event = \App\Models\Eventos::find($id);
Cobros::insert([
'turno_id' => $request->input("turno_id"),
'importe' => $request->input("importe"),
'servicio_id' => $request->input("servicio_id"),
]);
return view('cobrar',compact('cobros', 'evento', 'servicio', 'event'))->with($data);
}
Image Database:
I suggest adding a check to see if method is get or post...
public function cobrar(Request $request,$id){
$data = [
'category_name' => 'datatable',
'page_name' => 'custom',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$cliente = \App\Models\Eventos::first();
$cobros = \App\Models\Cobros::where('turno_id', $request->id)->first();
$evento = \App\Models\Eventos::where('id' , $id)->with('servicio')->first();
$servicio = \App\Models\Servicios::where('id', $evento->servicio_id)->first();
$event = \App\Models\Eventos::find($id);
if ($request->isMethod('post')) {
Cobros::insert([
'turno_id' => $request->input("turno_id"),
'importe' => $request->input("importe"),
'servicio_id' => $request->input("servicio_id"),
]);
}
return view('cobrar',compact('cobros', 'evento', 'servicio', 'event'))->with($data);
}

laravel 8 update eloquent relationships hasmany

My UPDATE function is as follows; I manually set some fields in the users table. In other words, it is necessary to update only the name part from the incoming request. If the lawyer has been removed from the edit form, it must also be removed from the users table. If the lawyer name has been updated, it should also be updated in the table.
How can I complete the update process.
public function update(Request $request, LegalPursuit $legalPursuit, $id)
{
$request->validate([
'BRANCH_ID' => 'required',
'MAIN_ACCOUNT_ID' => 'required',
'DEPOSITOR_ID' => 'required',
'ACCOUNT_HOLDER' => 'required|max:255',
'CURRENT_SCREEN_BALANCE' => 'required',
'TRL_EQUIVALENT' => 'required'
]);
//dd($request->all());
if($request->input('PROVISION') == 'on'){
$request->request->add(['PROVISION' => 'yes']);
}
$request->FOLLOW_UP_DATE = \Carbon\Carbon::parse($request->input('FOLLOW_UP_DATE'))->format('Y-m-d');
$request->DATE_OF_ATTORNEY_SUBMISSION = \Carbon\Carbon::parse($request->input('DATE_OF_ATTORNEY_SUBMISSION'))->format('Y-m-d');
$request->PROVISION_DATE = \Carbon\Carbon::parse($request->input('PROVISION_DATE'))->format('Y-m-d');
$request->request->add(['FOLLOW_UP_DATE' => $request->FOLLOW_UP_DATE]); //dd request
$request->request->add(['DATE_OF_ATTORNEY_SUBMISSION' => $request->DATE_OF_ATTORNEY_SUBMISSION]); //dd request
$request->request->add(['PROVISION_DATE' => $request->PROVISION_DATE]); //dd request
if(is_array($request->input('LAWYERS')) AND !empty($request->input('LAWYERS'))){
$lawyerArray = $request->input('LAWYERS');
//dd($lawyer_array);
$lawyerArray->each(function($lawyer) use ($user) {
$user->lawyerArray()->updateOrCreate(
[
'legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]
);
}
);
for($x = 0; $x < count($request->input('LAWYERS')); $x++){
User::updateOrInsert(
['legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]);
}
/*foreach($lawyer_array as $lawyer) {
$updateLaywer =
}
dd($updateLaywer);
/*
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$lawyersChanged = DB::table('users')
->whereIn('id', $getUsers)
->update(
[
'name' => ''
]
);
*/
//echo "asdfasdfasdf";exit;
/*
$lawyersChanged = User::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('LAWYERS')]
);
//echo $lawyersChanged; exit;*/
}else{
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$getUsers->delete();
//echo "aaaaaaaa";exit;
}
if(is_array($request->input('GUARANTORS')) AND !empty($request->input('GUARANTORS'))){
echo "asdfasdfadsf";exit;
$guarantorsChanged = Guarantors::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('GUARANTORS')]
);
}else{
//echo "hdfghdfghdfghdfgh";exit;
$getGuarantors = DB::table('guarantors')
->select(['guarantors.id'])
->leftJoin('legalpursuit', 'guarantors.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
//dd($getGuarantors);
//$getGuarantors->delete();
}
if($request->input('REMOVE_FILES')){
$getCurrentFiles = DB::table('files')
->select(['files.ID'])
->leftJoin('legalpursuit', 'files.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
}
LegalPursuit::where('ID',$id)->update(
$request->only(
[
'BRANCH_ID',
'MAIN_ACCOUNT_ID',
'DEPOSITOR_ID',
'ACCOUNT_HOLDER',
'FOLLOW_UP_DATE',
'CURRENT_SCREEN_BALANCE',
'CURRENCY',
'TRL_EQUIVALENT',
'DATE_OF_ATTORNEY_SUBMISSION',
'PROVISION',
'PROVISION_DATE',
'LAWSUIT_ID',
'ASSURANCE',
'DEED_PLATE',
'APPRAISAL_VALUE',
'LIEN_PRICE',
'DETERMINED_GUARANTEES',
'LEVY_INFO',
'LAST_STATUS'
]
)
);
if($request->hasFile('FILES')) {
foreach ($request->file('FILES') as $fl) {
$fileName = time().'_'.$fl->getClientOriginalName();
$fileExt = $fl->getClientOriginalExtension();
$filePath = $fl->store('public/files');
$filex = new Files;
$filex->legalpursuit_id = $id;
$filex->name = $fileName;
$filex->type = $fileExt;
$filex->label = $filePath;
$filex->descript = $fileName.'-'.$fileExt.'--'.$filePath;
$filex->status = 'on';
$filex->save();
}
}
return redirect()->back()->with('success', 'Kayıt Başarılı Bir Şekilde Güncellendi...');
}

Too few arguments to function App\Http\Controllers\RaveController::addToOrdersTables(), 0 passed and exactly 2 expected

Hi I am using RaveFlutterWave as my payment gateway. I want to store an orders whenever a customer finish making payment but I couldn't get pass that error. I don't know what am missing there.
Thanks for your help, here is my code.
public function callback(Request $request)
{
// $data = Rave::verifyTransaction(request()->txref);
$resp = $request->resp;
$body = json_decode($resp, true);
$txRef = $body['data']['data']['txRef'];
$data = Rave::verifyTransaction($txRef);
return redirect()->route('success');
}
Here is my route
Route::get('/success', 'RaveController#addToOrdersTables')->name('success');
and this is my method for saving the order
protected function addToOrdersTables($request, $error)
{
$order = Order::create([
'user_id' => auth()->user() ? auth()->user()->id : null,
'billing_email' => $request->email,
'billing_first_name' => $request->first_name,
'billing_last_name' => $request->last_name,
'billing_address' => $request->address,
'billing_city' => $request->city,
'billing_town' => $request->town,
'billing_postalcode' => $request->postalcode,
'billing_phone' => $request->phone,
'billing_total' => Cart::getTotal(),
'error' => $error,
]);
foreach (Cart::getContent() as $item)
{
OrderProduct::create([
'order_id' => $order->id,
'product_id' => $item->model->id,
'quantity' => $item->quantity,
]);
}
}
Thanks for concern.
You have to pass parameter through route as well:
Route::get('/success/{error}', 'RaveController#addToOrdersTables')->name('success');
And In addToOrdersTables method type hint the request using Request Like given below:
protected function addToOrdersTables(Request $request, $error)

How do I unit-test table filter function in lumen

This is the my back-end code. I wrote the test for this function as follows:
public function index(Request $request)
{
$fields = 'in:' . implode(',', Schema::getColumnListing('suppliers'));
$messages = [
'order_by.in' => 'The selected column name is invalid.',
];
$this->validate($request, [
'page' => ['numeric'],
'per_page' => ['numeric'],
'order_direction' => ['in:desc,asc,DESC,ASC'],
'order_by' => [$fields],
], $messages);
$perPage = 10;
$filter = '';
$orderBy = 'id';
$orderDirection = 'DESC';
try {
if ($request->has('per_page')) $perPage = (int)$request->per_page;
if ($request->has('filter')) $filter = $request->filter;
if ($request->has('order_by')) $orderBy = $request->order_by;
if ($request->has('order_direction')) $orderDirection = strtoupper($request->order_direction);
$suppliers = Supplier::select('id', 'firstname', 'lastname', 'phone', 'email', 'custom_field_1', 'custom_field_2')->where('store_id', Auth::user()->store);
if (!!$filter) {
$suppliers->where('id', 'LIKE', "%{$filter}%")
->orWhere('firstname', 'LIKE', "%{$filter}%")
->orWhere('lastname', 'LIKE', "%{$filter}%")
->orWhere('email', 'LIKE', "%{$filter}%")
->orWhere('phone', 'LIKE', "%{$filter}%");
}
$suppliers->orderBy($orderBy, $orderDirection);
$suppliers = $suppliers->paginate($perPage);
return response()->json([
'success' => true,
'data' => $suppliers->toArray(),
], Response::HTTP_OK);
} catch (Exception $e) {
report($e);
return serverExceptionMessage();
}
}
This is what I have tried and test. I'm creating a store because store_id is a foreign key in my supplier table and adding suppliers dynamically and filtering the firstname through the URL and getting the result from seeJson as an array:
public function testSupplierListViewPaginationFilterTest()
{
$user = factory('App\Models\User')->make();
$store = (factory('App\Models\Store')->make())->getAttributes();
$this->actingAs($user)
->post('/create-new-store', $store)
->seeStatusCode(Response::HTTP_OK);
$attributes = [
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
];
$user->store = Store::latest()->first()->id;
$attributes['store_id'] = Auth::user()->store;
$supplier = Supplier::create($attributes);
$this->actingAs($user)
->get('/suppliers?filter=' . $supplier['firstname'], $attributes)
->seeStatusCode(Response::HTTP_OK)->seeJson([
'success' => true,
"data" =>
[
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
]
]);
}
I'm getting following error:
1) SupplierTest::testSupplierListViewPaginationFilterTest
Unable to find JSON fragment
["data":"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":776358547}] within [{"data":{"current_page":1,"data":[{"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":"776358547"}],"first_page_url":"http:\/\/localhost\/suppliers?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/localhost\/suppliers?page=1","next_page_url":null,"path":"http:\/\/localhost\/suppliers","per_page":10,"prev_page_url":null,"to":1,"total":1},"success":true}].
Failed asserting that false is true.
I need a best solution for this problem .

Input data is not stored as expected in Laravel 6

I have form with dynamic tables in it where i can add/remove rows, I want to save the data into Transaction_in and Transaction_in_detail table, when i save the data to Transaction_in table is saved as expected but not with Transaction_in_detail.
When I submit the data no matter how many row I put inside the table the saved data inside Transaction_in_detail table always give me 10 all null rows.
Store Controller
public function store(Request $request)
{
$request->validate([
'supplier_id' => 'required',
'transaction_in_date' => 'required|before_or_equal:today',
'device_type_id' => 'required',
'device_brand_id' => 'required',
'device_spec' => 'required|max:255',
'price' => 'required',
'amount' => 'required',
'total_price' => 'required',
'keterangan' => 'Nullable',
]);
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_id');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
foreach ($transaction_in as $tin) {
$tdin[] = [
'Transaction_in_id' => $transaction_in->id[$tin],
'DeviceType_id' => $transaction_in->device_type_id[$tin],
'DeviceBrand_id' => $transaction_in->device_brand_id[$tin],
'spek_device' => $transaction_in->device_spec[$tin],
'harga_device' => $transaction_in->price[$tin],
'jumlah_device' => $transaction_in->amount[$tin],
'total_harga_device' => $transaction_in->total_price[$tin]
];
Transaction_in_detail::insert($tdin);
}
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
return redirect('/transactionsin')->with('success', 'Transaction success');
}
The following is the output from dd().
I don't know where the mistake is; this is the model.
Transaction_in Model
class Transaction_in extends Model
{
protected $guarded = [];
public function get_suppliers()
{
return $this->belongsTo(Supplier::class, 'Supplier_id');
}
public function get_devicetypes()
{
return $this->belongsToMany(DeviceType::class, 'DeviceType_id');
}
public function get_devicebrands()
{
return $this->belongsToMany(DeviceBrand::class, 'DeviceBrand_id');
}
}
Transaction_in_detail Model
class Transaction_in_detail extends Model
{
protected $guarded = [];
public function get_transction_in_id()
{
return $this->belongsTo(Transaction_in::class, 'Transaction_in_id');
}
public function get_devicetypes()
{
return $this->belongsToMany(DeviceType::class, 'DeviceType_id');
}
public function get_devicebrands()
{
return $this->belongsToMany(DeviceBrand::class, 'DeviceBrand_id');
}
}
The Form is inside Transaction_in View and that Store Controller is from transaction_inController, both DeviceType_id and DeviceBrand_id are foreign key.
This is Transaction_in table in database work as expected.
Remove foreach in your function and you can insert data directly to transaction in detail table
public function store(Request $request)
{
...
$transaction_in->save();
for($i=0; $i < count($request->device_brand_id); $i++){
$tdin[] = array(
'Transaction_in_id' => $transaction_in->id,
'DeviceType_id' => $request->device_type_id[$i],
'DeviceBrand_id' => $request->device_brand_id[$i],
'spek_device' => $request->device_spec[$i],
'harga_device' => $request->price[$i],
'jumlah_device' => $request->amount[$i],
'total_harga_device' => $request->total_price[$i]
);
}
Transaction_in_detail::insert($tdin);
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
return redirect('/transactionsin')->with('success', 'Transaction success');
}
Your store method is a bit weird, this is what I think you should be doing:
public function store(Request $request)
{
$request->validate([
'supplier_id' => 'required',
'transaction_in_date' => 'required|before_or_equal:today',
'device_type_id' => 'required',
'device_brand_id' => 'required',
'device_spec' => 'required|max:255',
'price' => 'required',
'amount' => 'required',
'total_price' => 'required',
'keterangan' => 'Nullable',
]);
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->get('supplier_id');
$transaction_in->tanggal_transaksi = $request->get('transaction_in_date');
$transaction_in->save();
Transaction_in_detail::create([
'Transaction_in_id' => $transaction_in->id,
'DeviceType_id' => $request->get('device_type_id'),
'DeviceBrand_id' => $request->get('device_brand_id'),
'spek_device' => $request->get('device_spec'),
'harga_device' => $request->get('price'),
'jumlah_device' => $request->get('amount'),
'total_harga_device' => $request->get('total_price')
]);
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
return redirect('/transactionsin')->with('success', 'Transaction success');
}
I think that all 10 rows became null because of the looping takes the count of the table columns.
your code
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_id');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
foreach ( $transaction_in as $tin) {
$tdin[] = [
'Transaction_in_id' => $transaction_in->id[$tin],
'DeviceType_id' => $transaction_in->device_type_id[$tin],
'DeviceBrand_id' => $transaction_in->device_brand_id[$tin],
'spek_device' => $transaction_in->device_spec[$tin],
'harga_device' => $transaction_in->price[$tin],
'jumlah_device' => $transaction_in->amount[$tin],
'total_harga_device' => $transaction_in->total_price[$tin]
];
Transaction_in_detail::insert($tdin);
}
My Code
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_id');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
$transaction_in1 = new Transaction_in();
foreach ( $transaction_in1 as $tin) {
$tdin[] = [
'Transaction_in_id' => $transaction_in1->id[$tin],
'DeviceType_id' => $transaction_in1->device_type_id[$tin],
'DeviceBrand_id' => $transaction_in1->device_brand_id[$tin],
'spek_device' => $transaction_in1->device_spec[$tin],
'harga_device' => $transaction_in1->price[$tin],
'jumlah_device' => $transaction_in1->amount[$tin],
'total_harga_device' => $transaction_in1->total_price[$tin]
];
Transaction_in_detail::insert($tdin);
}

Categories