I have table dosen (iddosen, user_id, namadosen, notelpdosen, fotodosen, etc)
I try to register a user + upload photo, but it came with 2 row inserted.
all columns are null, except "fotodosen"
all row has data, except "fotodosen".
This is my method :
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => $request->input('password'),
'admin' => $request->input('admin'),
]);
$dosen = Dosen::create([
'iddosen' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
'tempatlahirdosen' => $request->input('tempatlahirdosen'),
'tanggallahirdosen' => $request->input('tanggallahirdosen'),
'agamadosen' => $request->input('agamadosen'),
]);
if ($request->hasFile('image')) {
$data = $request->input('image');
$photo = $request->file('image')->getClientOriginalName();
$destination = public_path() . '/uploads/';
$request->file('image')->move($destination, $photo);
$data['fotodosen'] = $photo;
Dosen::create($data);
}
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
Please correct my code
You are using Dosen::create twice there for a new row for each usage.
append $data to request or try this :
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => $request->input('password'),
'admin' => $request->input('admin'),
]);
if ($request->hasFile('image')) {
$data = $request->input('image');
$photo = $request->file('image')->getClientOriginalName();
$destination = public_path() . '/uploads/';
$request->file('image')->move($destination, $photo);
$data['fotodosen'] = $photo;
}
$dosen = Dosen::create([
'iddosen' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
'tempatlahirdosen' => $request->input('tempatlahirdosen'),
'tanggallahirdosen' => $request->input('tanggallahirdosen'),
'agamadosen' => $request->input('agamadosen'),
'fotodosen' => $photo, //you have to add it hear
]);
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
Related
I would like to update a form, I mentioned that the form is already saved in the database(function store). I want to edit the form and update it in the database(function update).
I only want to UPDATE the "tags", this is giving me an error because it is in another table.
I would need your help because I can't do it, I tried different methods but didn't succeed.
public function store(Request $request)
{
// process the listing creation form
$validationArray = [
'title' => 'required',
'company' => 'required',
'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:9048',
'location' => 'required',
'service' => 'required',
'apply_link' => 'required|url',
'content' => 'required',
'payment_method_id' => 'required'
];
if (!Auth::check()) {
$validationArray = array_merge($validationArray, [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:5',
'name' => 'required',
'phone' => 'required|numeric|min:10|starts_with:0'
]);
}
$request->validate($validationArray);
// is a user signed in ? if not, create one and authenticate
$user = Auth::user();
if (!$user) {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone' => $request->phone
]);
$user->createAsStripeCustomer();
Auth::login($user);
}
// process the payment and create the listing
try {
$amount = 9900; // $99.00 USD in cents
if ($request->filled('is_highlighted')) {
$amount += 1000;
}
$user->charge($amount, $request->payment_method_id);
$md = new \ParsedownExtra();
$listing = $user->listings()
->create([
'title' => $request->title,
'slug' => Str::slug($request->title) . '-' . rand(1111, 9999),
'company' => $request->company,
'logo' => basename($request->file('logo')->store('public')),
'location' => $request->location,
'apply_link' => $request->apply_link,
'content' => $md->text($request->input('content')),
'is_highlighted' => $request->filled('is_highlighted'),
'is_active' => true
]);
**foreach (explode(',', $request->tags) as $requestTag) {
$tag = Tag::firstOrCreate([
'slug' => Str::slug(trim($requestTag))
], [
'name' => ucwords(trim($requestTag))
]);
$tag->listings()->attach($listing->id);
}**
foreach (explode(',', $request->service) as $requestService) {
$service = Service::firstOrCreate([
'service_name' => ucwords(trim($requestService))
]);
$service->listings()->attach($listing->id);
}
return redirect()->route('user.dashboard')->with('success', 'Anuntul tau a fost publicat!');
} catch (\Exception $e) {
return redirect()->back()
->withErrors(['error' => $e->getMessage()]);
}
} $tag->listings()->attach($listing->id);
}
public function edit($id)
{
$listing = Listing::findOrFail($id);
if (Auth::check() && Auth::user()->id == $listing->user_id) {
$listing = DB::table('listings')
->where('id', $id)
->first();
return view('listings.edit', compact('listing'));
} else {
return (redirect('/dashboard'));
}
}
public function update(Request $request, $id)
{
//working in progress...
$this->validate($request,[
'title' => 'required',
'company' => 'required',
'logo' => 'file|max:2048|required|mimes:jpeg,jpg,png',
'location' => 'required',
'apply_link' => 'required|url',
'content' => 'required'
// 'payment_method_id' => 'required'
]);
$data = Listing::find($id);
$data->title = $request->title;
$data->company = $request->company;
$data->logo = basename($request->file('logo')->store('public'));
$data->location = $request->location;
$data->apply_link = $request->apply_link;
$data['tags'] = explode(',', $request->tags); // <-this one
$data->content= $request->content;
// $data['is_highlighted'] = $request->is_highlighted;
$data['user_id'] = Auth::user()->id;
$data->save();
// DB::table('listings')->where('id', $id)->update($data);
return redirect()->back()->with('success', 'success');
}
I try to import Excel to Laravel when some field merges as JSON in the customer's table. In my case, I try to merge some fields like berar_badan, usia, etc., on the other_data field. I tried this code but failed.
$this->validate($request, [
'file' => 'required|mimes:csv,xls,xlsx'
]);
$file = $request->file('file');
$data = Excel::toArray(new CustomerImport, $file);
DB::beginTransaction();
try {
foreach ($data[0] as $d) {
//skip header
if ($d == 0) {
continue;
}
$email = Customer::where('email', $d['email_address'])->first();
$otherData = array_shift($d);
if (!$email) {
$customer = Customer::create([
// 'source' => $d['source'],
'source_detail' => $d['source_detail'],
'source_sub_detail' => $d['source_detail'],
'name' => $d['customer_name'],
'phone_1' => $d['phone_number_1'],
'email' => $d['email_address'],
'dob' => $d['dob'],
'address' => $d['address'],
'village' => $d['kelurahan'],
'district' => $d['kecamatan'],
'regency' => $d['kabupaten'],
'province' => $d['provinsi'],
'hpl' => $d['hpl'],
'parent_type' => $d['parent_type'],
'password' => Hash::make($d['phone_number_1']),
'client_id' => Session::get('client_id'),
'other_data' => $otherData
]);
DB::table('customer_children')->insert([
'customer_id' => $customer->id,
'name' => $d['child_name'],
'dob' => $d['child_dob'],
'gender' => $d['children_gender'],
'created_at' => Carbon::now(),
]);
}
}
DB::commit();
Alert::success('Success', 'Success upload data customer.');
return redirect()->back();
}
I have four tables
default_products_product_mileage_gap
default_products_mileage_gap
default_products_products
default_products_products_mileage_gaps
I am trying to update a column number_of_products_sold to some value using laravel
What I have tried is:
$qty = 1;
$m = DB::table('products_products')
->join(
'products_products_mileage_gaps',
'products_products.id',
'=',
'products_products_mileage_gaps.entry_id'
)
->join(
'products_product_mileage_gap',
'products_products_mileage_gaps.related_id',
'=',
'products_product_mileage_gap.id'
)
->join(
'products_mileage_gap',
'products_mileage_gap.id',
'=',
'products_product_mileage_gap.mileage_gap_id'
)
->where('products_product_mileage_gap.number_of_products', '>', 0)
->where('products_mileage_gap.name', '=', $mileage_name)
->where('products_products.id', '=', $id)
->update(
array(
'products_product_mileage_gap.number_of_products_sold' => $qty
)
);
Here number_of_products_sold is not updating.
How to update the column
Why you want to add four table together. here is an example to add or update multiple table from by controller.
public function processEmployee(Request $request)
{
$data = $request->all();
$user = User::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$emp = Employee::create([
'photo' => $emp_image,
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'qualification' => $data['qualification'],
'emergency_number' => $data['emer_number'],
'pan_number' => $data['pan_number'],
'father_name' => $data['father_name'],
'current_address ' => $data['current_address'],
'permanent_address' => $data['permanent_address'],
'formalities' => $data['formalities'],
'offer_acceptance' => $data['offer_acceptance'],
'probation_period' => $data['prob_period'],
'department' => $data['department'],
'salary' => $data['salary'],
'account_number' => $data['account_number'],
'bank_name' => $data['bank_name'],
'ifsc_code' => $data['ifsc_code'],
'pf_account_number' => $data['pf_account_number'],
'un_number' => $data['un_number'],
'pf_status' => $data['pf_status'],
'user_id' => $user->id,
]);
$userRole = UserRole::create([
'role_id' => $data['role'],
'user_id' => $user->id,
]),
]);
if(isset($emp, $user, $userRole)) {
return redirect()->route('employee-manager')
->with('message',
'Employee Successfully Registered.');
}else{
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())->with('error',
'Action Failed Please try again.');
}
}
I need the filled field remains its input data. but this happened it's gone. What should I do to make it still remain? I used Laravel 5.4. already used this command " $req->flash(); " but still failed
Here is my output
and this is my code:
public function register_create(Request $req) {
$req->flash();
$req->validate([
'name' => 'required',
'matrix-number' => 'required',
'ic-number' => 'required',
'faculty' => 'required',
'programme' => 'required',
'part' => 'required',
'group' => 'required',
'email' => 'required',
'phone-number' => 'required'
]);
$name = Helpers::raw($req->input('name'));
$matrix_number = $req->input('matrix-number');
$ic_number = $req->input('ic-number');
$faculty = Helpers::raw($req->input('faculty'));
$programme = $req->input('programme');
$part = $req->input('part');
$group = $req->input('group');
$email = $req->input('email');
$phone_number = $req->input('phone-number');
User::create([
'name' => $name,
'matrix_number' => $matrix_number,
'ic_number' => $ic_number,
'faculty' => $faculty,
'programme' => $programme,
'part' => $part,
'group' => $group,
'email' => $email,
'phone_number' => $phone_number,
'password' => $ic_number
]);
{
if (session('validate')) {
$req -> validate;
return redirect()->action('HomeController#login');
}
else
{
$req->session()->reflash();
$req->session()->put('some_key', $req->all());
return redirect()->back()->withInput();
}
}
}
i want to give user free deposit after registration.therefore i want to fill "deposit" table along with "users" table. i have tried below but i am getting error.
protected function create(array $data)
{
$basic = BasicSetting::first();
$status = $basic->verify_status == 1 ? '0' : '1';
$image25 = 'user-default.png';
if ($basic->reference_id == $data['reference']){
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'under_reference' => $data['reference'],
'password' => bcrypt($data['password']),
'verifyToken' => Str::random(40),
'reference' => Str::random(12),
'status' => $status,
'image' => $image25
]);
$Deposit = Deposit::create([
'deposit_number' => date('ymd').Str::random(6).rand(11,99),
'plan_id' => $data['planid'],
'percent' => $data['percent'],
'time' => $data['time'],
'compound_id' => $data['comp'],
'status' = $status
]);
You have a typo:
'status' = $status
should be
'status' => $status
At
$Deposit = Deposit::create([
'deposit_number' => date('ymd').Str::random(6).rand(11,99),
'plan_id' => $data['planid'],
'percent' => $data['percent'],
'time' => $data['time'],
'compound_id' => $data['comp'],
'status' = $status // <------------
]);
By the way, one best practice here is to use a transaction, because, if there is any error it will rollback both inserts.
So, your code could be:
if ($basic->reference_id == $data['reference']){
\DB::transaction(function() use($data) {
$basic = BasicSetting::first();
$status = $basic->verify_status == 1 ? '0' : '1';
$image25 = 'user-default.png';
$user = User::create([ .... ]);
$Deposit = Deposit::create([...]);
});
}