I can't seem to find the variable itinerary from my update function in my controller. What seems to be the problem for this?
Error says: Undefined variable: itinerary (View: C:\xampp\htdocs\project_name\resources\views\Agent\edit.blade.php)
AgentsController update function
public function update(Request $request, $p_id){
$this->validate($request, [
'packageName' => 'required',
'adultPrice' => 'required',
'childPrice' => 'required',
'infantPrice' => 'required',
'excessPrice' => 'required',
'type' => 'required',
'inclusions' => 'required',
'additionalInfo' => 'required',
'reminders' => 'required',
'photo' => 'required',
'tags' => 'required',
'noOfDays' => 'required',
'day' => 'required',
'time' => 'required',
'destination' => 'required'
]);
$packages = Packages::find($p_id);
$packages->packageName = $request->input('packageName');
$packages->adultPrice = $request->input('adultPrice');
$packages->childPrice = $request->input('childPrice');
$packages->infantPrice = $request->input('infantPrice');
$packages->excessPrice = $request->input('excessPrice');
$packages->type = $request->input('type');
$packages->inclusions = $request->input('inclusions');
$packages->additionalInfo = $request->input('additionalInfo');
$packages->reminders = $request->input('reminders');
$packages->photo = $request->input('photo');
$packages->tags = $request->input('tags');
$packages->save();
$itinerary = Itinerary::find($p_id);
if($itinerary->p_id == $packages->p_id){
$itinerary->noOfDays = $request->input('noOfDays');
$itinerary->day = $request->input('day');
$itinerary->time = $request->input('time');
$itinerary->destination = $request->input('destination');
$itinerary->save();
return redirect('Agent/Packages')->with('success', 'Updated');
}
}
edit.blade.php where the error is located
{{!!Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('AgentsController#update', $packages->p_id, $itinerary->p_id)))!!}}
Itinerary.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Itinerary extends Model{
public $fillable = [
'p_id',
'noOfDays',
'day',
'time',
'destination'
];
protected $primaryKey = 'i_id';
}
?>
Edit function
public function edit($p_id){
$packages = Packages::find($p_id);
$itinerary = Itinerary::find($p_id);
return View::make('\Agent\Edit', ['packages' => $packages, 'itineraries' => $itinerary]);
}
The way you pass the data is wrong.
Documentation
There are few ways you can pass. Examples :
1 -
return View::make('Agent.edit', ['packages' => $packages, 'itinerary' => $itinerary]);
2 - return View::make('Agent.edit')->with(['packages' => $packages, 'itinerary' => $itinerary]);
3 - return View::make('Agent.edit')->with('packages', $packages)->with('itinerary', $itinerary);
In your edit.blade.php, try remplacing your $itinerary variable by $itineraries (plural).
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'm Importing a CSV file to a livewire component and trying to run some validation for each row of the file but I'm having problems doing this. It seems that my validation is doing nothing.
Here is how my Livewire component looks like:
namespace App\Http\Livewire\Modals;
use Validator;
use Livewire\Component;
use App\Http\Traits\Csv;
use App\Models\AccountUser;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
class ImportExtensions extends Component
{
use WithFileUploads;
public $clientID;
public $showModal = false;
public $upload;
public $columns;
public $fieldColumnMap = [
'first_name' => '',
'last_name' => '',
'email' => '',
'password' => '',
'extension' => '',
'user_type' => '',
];
protected $rules = [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.extension' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|max:255',
];
protected $validationAttributes = [
'fieldColumnMap.first_name' => 'First Name',
'fieldColumnMap.last_name' => 'Last Name',
'fieldColumnMap.email' => 'Email',
'fieldColumnMap.password' => 'Password',
'fieldColumnMap.extension' => 'Extension',
'fieldColumnMap.user_type' => 'User Type',
];
public function updatingUpload($value)
{
Validator::make(
['upload' => $value],
['upload' => 'required|mimes:txt,csv'],
)->validate();
}
public function updatedUpload()
{
$this->columns = Csv::from($this->upload)->columns();
$this->guessWhichColumnsMapToWhichFields();
}
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
//Validate the data of each Row to make to make sure you don't import duplicate records
$this->validateOnly(collect($eachRow), [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255|email|unique:account_users, email',
'fieldColumnMap.extension' => 'required|numeric|unique:account_users, extension',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|in:user,admin',
]);
//If validation fails, it should skip the create extension part and run the next row
//If validation pass, then create the Extension
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
});
$this->reset();
$this->emit('refreshExtensions');
$this->notify('Successfully Imported '.$importCount.' Extensions');
}
Also, how can I make so that if the validation fails it goes to the next row instead of trying to create the extension.
Thanks.
I was able to create custom rules for just this. if one row fails validation, I just throw an error. So, basically either all rows pass or all fails.
Here is how it looks like now:
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
$validatedData = Validator::make([
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
],[
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:account_users',
'extension' => 'required|numeric|unique:account_users',
'password' => 'required|max:255',
'user_type' => 'required|in:user,admin',
],);
if($validatedData->fails()){
$this->notify(['error','Oops something went wrong!']);
}else{
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
}
});
$this->reset();
$this->emit('refreshExtensions');
if($importCount!=0) $this->notify(['success','Successfully Imported '.$importCount.' Extensions']);
}
I want to know how can I save two models which has one relationship in my models. I don't know how to save it but I need the ID for my patient model to assign to my scale model.
Here is my PatientController.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$scales = new Scale;
$patient->name = $request->input('name');
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->save();
return redirect('/patients')->with('success', 'Paciente creado.');
}
I try this code but get error.
DB::transaction(function() use ($patient, $scales) {
$patient = $patient->save(); //Patient Exists First
Patient::find($patient->id)->scales()->save($scales)
});
You could try something like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->name;
$patient->save();
$patient->scale()->create(['patient_id' => $patient->id, 'sd_abc_1_old' => $request->sd_abc_1_old]);
);
return redirect('/patients')->with('success', 'Paciente creado.');
}
If the model uses a hasOne() relation like you said then the code show work, with a bit of modification of course.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = Patient::create([
'name' => $request->input('name'),
]);
$scale = Scale::create([
'patient_id' => $patient->id,
'sd_abc_1_old' => $request->sd_abc_1_old,
]);
return redirect('/patients')->with('success', 'Paciente creado.');
}
First create and store base model and referencing it save related model
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->input('name');
$patient->save();
$scales = new Scale;
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->scales()->save($scales);
return redirect('/patients')->with('success', 'Paciente creado.');
}
I'm trying to get the ticket data to save in the database and when I submit the form I get no error, but it does not insert the data into the database. Added my Route just adding random text because the post
Controller Code
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'title' => 'required|min:15',
'category' => 'required',
'priority' => 'required',
'message' => 'required|min:100',
]);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'category_id' => $request->input('category'),
'ticket_id' => strtoupper(str_random(10)),
'name' => $request->input('name'),
'title' => $request->input('title'),
'priority_id' => $request->input('priority'),
'message' => $request->input('message'),
]);
$ticket->status_id = '1';
$ticket->save();
return 'Success';
}
Model Code
class Ticket extends Model
{
protected $fillable = [
'user_id', 'category_id', 'ticket_id', 'name', 'title', 'priority_id', 'message', 'status_id',
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function priority()
{
return $this->belongsTo(Priority::class);
}
public function status()
{
return $this->belongsTo(Status::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Routes
Route::get('/', 'HomeController#index')->name('home');
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/compliance', 'HomeController#Compliance')->name('compliance');
Route::get('/messages', 'HomeController#Messages')->name('messages');
Route::get('/tickets', 'TicketsController#userTickets')->name('tickets');
Route::get('/tickets/create', 'TicketsController#create')->name('tickets/create');
Route::post('/tickets/store', 'TicketsController#store');
Thanks for all the help I figured it I had two mistakes in the controller this took me 2 days to figure it out LOL
$this->validate($request, [
'name' => 'required', // I removed this
'title' => 'required|min:15',
'category' => 'required',
'priority' => 'required',
'message' => 'required|min:100',
]);
and in the $ticket
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'category_id' => $request->input('category'),
'ticket_id' => strtoupper(str_random(10)),
'name' => $request->input('name') // I replaced this with 'name' => Auth::user()->name,
'title' => $request->input('title'),
'priority_id' => $request->input('priority'),
'message' => $request->input('message'),
]);
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.