Laravel store and update form - php

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');
}

Related

How to store some field as Json when importing Excel in Laravel

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();
}

Laravel Input Data To the Session When the User Did Not Fill Up The Required Field

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();
}
}
}

Laravel 5.2 Modify Request After Form Validation Before Controller

I'm using laravel 5.2 and i'm using Form Request that given by laravel vendor to make my code clean, so i don't have many code on my controller :
public function store( CouponRequest $request )
{
DB::beginTransaction();
try {
$coupon = Coupon::create( $request->all() );
DB::commit();
return redirect()->route('admin.coupons.index');
} catch (\Exception $e) {
DB::rollback();
return redirect()->back()->withInput();
}
And this is my sample code about my request form :
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
Where should i place this command? :
$start_date = Carbon::create( $request->start_year, $request->start_month, $request->start_day );
$start_date->setTimeFromTimeString( $request->start_time );
$finish_date = Carbon::create( $request->finish_year, $request->finish_month, $request->finish_day );
$finish_date->setTimeFromTimeString( $request->finish_time );
If i place this code before validation, i could be error when some field not filled well by users.
So what i want is to place this code after validation success, but i don't want to place it at my controller.
Is there FormRequest function that can be called after validation success to modify my request??
I think it's not good when there's much code at controller, so i want to minimalize my controller code.
I am going to attempt this using FormRequest. If the intention here is to both validate and assign start_date and finish_date, this is probably the plausible way of doing so in Laravel:
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
/**
* #inheritDoc
*
* This method overrides Laravel's defeault FormRequest
* to create validator with `after()` hook
*/
protected function validator($validator)
{
$validator
->make(
$this->validationData(), $this->rules(), $this->messages(), $this->attributes()
)
->after(function($validator) {
if ($date = $this->getCarbonInstanceFromPrefix('start')) {
$request->start_date = $date;
} else {
$validator->errors()
->add('start_year', 'Invalid starting date and time');
}
if ($date = $this->getCarbonInstanceFromPrefix('finish')) {
$request->finish_year = $date;
} else {
$validator->errors()
->add('finish_year', 'Invalid finish date and time');
}
});
}
/**
* Retrieve carbon instance from current request, using prefix
*
* #param string $prefix
*
* #return Carbon|null
*/
protected function getCarbonInstanceFromPrefix($prefix = '')
{
try {
$date = Carbon::create(
$request->get($prefix . '_year'),
$request->get($prefix . '_month'),
$request->get($prefix . '_day')
);
$date->setTimeFromTimeString( $request->get($prefix . '_time') );
return $date;
} catch (\Exception $e) {
return null;
}
}
Quick Explanation
FormRequest essentially extends from Illuminate\Foundation\Http\FormRequest and can override the method where instance of Validator is created. By creating your custom validator, you can attach after() event to both validate each date inputs, and also assign additional parameter to request in one go.

Laravel 5.2 | double insert data in single request

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!');
}

BadMethodCallException Method [ register] does not exist

I'm trying to get my registration page to show, the controller logic seems ok but I keep getting this:
BadMethodCallException
Method [ register] does not exist.
here is my controller logic:
<?php
class UserController extends BaseController {
public function register()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.register")->with("title", "Avenue - Register")->with("page_title", "Register");
}
public function postRegister()
{
$rules = array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('register')->with_input()->with_errors($validation);
}
$user = Sentry::createUser(array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'email' => Input::get('email'),
'password' => Input::get('password'),
'metadata' => array(
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
'nationality' => Input::get('nationality'),
'gender' => Input::get('gender'),
'category' => Input::get('category'),
),
));
Mail::send('emails.welcome', $data, function($message)
{
$message->to(Input::get('email'))->subject('Welcome to Avenue254!');
});
}
public function getLogin()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.login")->with("title","Avenue254 - Login")->with("page_title","Login");
}
public function postLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return Redirect::to_route('login')->with_errors($validation->errors)->with_input();
}
$credentials = array( 'email'=> Input::get('email'), 'password'=>Input::get('password') );
if (Sentry::authenticate($credentials, false))
{
return Redirect::to('myaccount');
}
else
{
return Redirect::to('login')->with("error", "There is problem with login please try again");
}
}
public function getMyaccount()
{
if(!Sentry::check()){
return Redirect::to('login')->with("error", "Please login to access your account");
}
$user = Sentry::getUser();
return View::make("users.myaccount")->with("title","Avenue254" - "My Account")->with("page_title","My Account")->with('user',$user);
}
public function postProfile()
{
$user = Sentry::getUser();
$rules = array(
'email' => 'required|email|unique:users,email,'.$user['id'],
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('myaccount')->with_input()->with_errors($validation);
}
$user_data = array(
'email' => Input::get('email'),
'metadata' => array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
),
);
if ($user->update($user_data))
{
return Redirect::to('myaccount')->with('success', 'Your information has been updated successfully.');
}
else
{
return Redirect::to('myaccount')->with('error', 'Something went wrong!.');
}
}
}
and my routes:
Route::get('register', array('as' => 'getregister', 'uses' => 'UserController#
register'));
Route::get('myaccount', array('as' => 'myaccount', 'uses' => 'UserController#
myaccount'));
Route::post('register', array('as' => 'postregister', 'uses' =>
'UserController#postRegister'));
Whenever I try to route to register I get this error, I have tried everything unsuccessfully. What could I be doing wrong?

Categories