Creating default object from empty value using laravel 6 and ajax - ajax
i have in an annonces table a multiple images, i want to update multiple images, but it gives me error:
Creating default object from empty value knowing that i tried to transform multipleimage to a given json.in the console it gives me the name of the images to select.
AnnoncesController.php
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::find($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
$path = $request->images->store('annonces');
$Annonce->images = $path;
array_push($data,$path);
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
web.php
Route::post('annonces/filesUpdate','AnnoncesController#filesUpdate');
details.blade.php
<form method="post" action="{{url('annonces/filesUpdate')}}" enctype="multipart/form-data"
class="dropzone" id="dropzone">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
<script type="text/javascript">
Dropzone.options.dropzone =
{
maxFilesize: 12,
renameFile: function(file) {
var dt = new Date();
var time = dt.getTime();
var images = time+file.name
console.log(time+file.name);
return images;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
success: function(file, response)
{
console.log(response);
},
error: function(file, response)
{
return false;
}
};
</script>
You are not passing the id as route parameter in the form action so the $id value received in filesUptate method in controller will be null. You have to pass the $Annonce->id as route parameter via form action
//When you send this view as response from edit method you need to pass
//either $Annonce object or at least the $Annonce->id as $AnnonceId to the view
//If you pass the entire $Annonce object then append $Annonce->id as below
//to the form action or replace it with $AnnonceId if you are passing only
//$AnnonceId from the edit method of the controller
<form
method="post"
action="{{url('annonces/filesUpdate/' . $Annonce->id)}}"
enctype="multipart/form-data"
class="dropzone" id="dropzone"
>
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
The error probably arises as you are trying to call store method on array.
Try the below
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::findOrFail($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
//Trying to call store on an array here
//$request->images is not an instance of UploadedFile
//$path = $request->images->store('annonces');
//$file is an instance of UploadedFile
//so you can call store method on it
$data[] = $file->store('annonces');
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
You can also use $casts property to let Laravel handle the casting of images attribute automatically
class Annonce extends Model
{
protected $casts = [ 'images' => 'array'];
}
Related
stripe payment method is returning null when I submit form
when I try to create a new subscription I get this error (This customer has no attached payment source or default payment method. ) so I checked the PaymentController with dd($paymentMethod) which returned null so I don't know why the variable $paymentMethod in store method is returning NULL from the $request but the request, for the price is returning the price_id. Please any help is appreciated but when console.log() setupIntent.payment_method it returned the payment_method in the console Here is my PaymentController public function index() { $availablePlans = [ 'price_1HnIiLLzAo4pwMcyh2aGaznB' => 'Monthly', 'price_1HnJ2vLzAo4pwMcygQT66juk' => 'Yearly', 'price_1HnIhILzAo4pwMcy9iH3j30L' => 'Free Membership' ]; $user = auth()->user(); $data = [ 'intent' => $user->createSetupIntent(), 'plans' => $availablePlans ]; return view('payments.checkout')->with($data); } public function store(Request $request) { $user = auth()->user(); $paymentMethod = $request->payment_method; // dd($paymentMethod); $planId = $request->plan; $user->newSubscription('premium', $planId)->create($paymentMethod); return response(['status' => 'success']); } This is the Javascript window.addEventListener('load', function (){ // Create a Stripe client. const stripe = Stripe('pk_test_51H2OqqLzAo4pwMcyT4h405wpFRAn3FWhvByfvmVnW6tabrIsDoU1dBXJ0UaWexUJeacCJ9uKpb5OBmmA2KaCg4sd00ZZ5tj2q8'); // Create an instance of Elements. const elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. // (Note that this demo uses a wider set of styles than the guide below.) // const cardElement = elements.create('card', {style: style}); // Create an instance of the card Element. const cardElement = elements.create('card'); // Add an instance of the card Element into the `card-element` <div>. cardElement.mount('#card-element'); const cardHolderName = document.getElementById('card-holder-name'); const cardButton = document.getElementById('card-button'); const clientSecret = cardButton.dataset.secret; const plan = document.getElementById('subscription-plan').value; cardButton.addEventListener('click', async (e) => { const { setupIntent, error } = await stripe.handleCardSetup( clientSecret, cardElement, { payment_method_data: { billing_details: { name: cardHolderName.value } } } ); if (error) { // Display "error.message" to the user... } else { // The card has been verified successfully... // console.log('handling success', setupIntent.payment_method); axios.post('/subscribe', { payment_method: setupIntent.payment_method, plan: plan }) } }); }); Here is the form <form action="{{ route('subscribe')}}" method="POST" id=""> #csrf <div class="form-content"> <div class="field"> <select class="form-control" name="plan" id="subscription-plan"> #foreach ($plans as $key=>$plan ) <option value="{{$key}}">{{$plan}}</option> #endforeach </select> </div> <div class="field"> <input type="text" autocorrect="off" spellcheck="false" id="card-holder-name" maxlength="25" /> <span class="focus-bar"></span> <label for="cardholder">Card holder (Name on card)</label> </div> <div class="field mb-5" id="card-element"> <!-- Stripe Elements Placeholder --> </div> <button id="card-button" data-secret="{{ $intent->client_secret }}"><span>Pay</span></button> </div> </form> The Route Route::resource('payments', 'PaymentsController', [ 'names'=> [ 'index' => 'checkout', 'store' => 'subscribe', ] ]);
Looks like there is something wrong with how you're using axios. Have you tried taking a look at laravel simple axios with argument
Adding a hidden input field in the form and setting the value to setupIntent.payment_method passed the payment_method id to the controller which is used to create the subscription so the problem is solved. A few modifications and adding a hidden input field to the JS // Handle form submission. var form = document.getElementById('payment-form'); form.addEventListener('submit', async (e) => { e.preventDefault(); //cardButton.addEventListener('click', async (e) => { //e.preventDefault() const { setupIntent, error } = await stripe.handleCardSetup( clientSecret, cardElement, { payment_method_data: { billing_details: { name: cardHolderName.value } } } ); if (error) { // Display "error.message" to the user... } else { // The card has been verified successfully... //console.log('handling success', setupIntent.payment_method); axios.post('/subscribe',{ plan : plan }) var paymentMethod = setupIntent.payment_method; var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'payment_method'); hiddenInput.setAttribute('value', paymentMethod); form.appendChild(hiddenInput); // Submit the form form.submit(); }
laravel-5.8:The POST method is not supported for this route. Supported methods: GET, HEAD
hi m trying to add products in cart but it says: The POST method is not supported for this route. Supported methods: GET, HEAD.. (View: \resources\views\product\detail.blade.php), I wants that by clicking the addtocart it redirect me to that age with products,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,...…………………………………..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, route: Route::get('cart', 'Admin\ProductController#cart')->name('product.cart'); Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart'); controller: public function cart() { if (!Session::has('cart')) { return view('products.cart'); } $cart = Session::has('cart'); return view('product.cart', compact('cart')); } public function addToCart(Product $product, Request $request) { if(empty(Auth::user()->email)){ $data['email'] = ''; }else{ $data['email'] = Auth::user()->email; } $oldCart = Session::has('cart') ? Session::get('cart') : null; $qty = $request->qty ? $request->qty : 1; $cart = new Cart($oldCart); $cart->addProduct($product); Session::put('cart', $cart); return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart'); } view: <form method="POST" action="{{ route('addToCart') }}" enctype="multipart/form-data"> <div class="btn-addcart-product-detail size9 trans-0-4 m-t-10 m-b-10"> #if($product->product_status == 1) <!-- Button --> <button class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4"> Add to Cart </button> #else Out Of Stock #endif </div> </form> model: <?php namespace App; use Illuminate\Database\Eloquent\Model; class Cart { private $contents; private $totalQty; private $contentsPrice; public function __construct($oldCart){ if ($oldCart) { $this->contents = $oldCart->contents; $this->totalQty = $oldCart->totalQty; $this->totalPrice = $oldCart->totalPrice; } } public function addProduct($product, $qty){ $products = ['qty' => 0, 'price' => $product->price, 'product' => $product]; if ($this->contents) { if (array_key_exists($product->slug, $this->contents)) { $product = $this->contents[$product->slug]; } } $products['qty'] +=$qty; $products['price'] +=$product->price * $product['qty']; $this->contents[$product->slug] = $product; $this->totalQty+=$qty; $this->totalPrice += $product->price; } public function getContents() { return $this->contents; } public function getTotalQty() { return $this->totalQty; } public function getTotalPrice() { return $this->totalPrice; } }
First of all your form method in the view is POST but you don't have a post route. Second, the route that you have defined expect a parameter(product) you can change the form action as below BUT I think you want to send the user to another page so you can use a link instead of form. Here's the form action: action="{{ route('addToCart', $product->id) }}" And if you want to use link, you can do something like this: .....
Your method should be POST. In the form, you're calling it Post method but in route.php file, you defined as get to change it as Route::post Route::post('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart'); In addition, your route.php file expecting {product} so you need to pass it in form route so your action be like {{ route('addToCart',$product->id) }} <form method="POST" action="{{ route('addToCart',$product->id) }}" enctype="multipart/form-data"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> </form>
how do i pass data value to another page via link in laravel?
i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location this is what ive done now but i keep getting the error: Call to undefined method App\Reservation::location() as soon as i have filled in the fields of information this is the blade file that links to the the create reservation file #foreach ($locations as $location => $data) <tr> <th>{{$data->id}}</th> <th>{{$data->name}}</th> <th>{{$data->type}}</th> <th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th> </tr> #endforeach this is the create reservations blade <form action="{{ route('location.store') }}" method="post"> #csrf <label>title</label> <input type="text" class="form-control" name="name"/> <label>type</label> <select> <option value="0">klein</option> <option value="1">groot</option> </select> <button type="submit" class="btn">inschrijven</button> </form> this is what the location controller looks like public function store(Request $request) { $location = new Reservation; $location->name = $request->get('name'); $location->type = $request->get('type'); $location->location()->associate($request->location()); $location->save(); return redirect('/location'); } and the relationships in my models should also work class Reservation extends Model { public function locations() { return $this->belongsTo('Location::class'); } } class Location extends Model { public function reservations() { return $this->hasMany('Registration::class'); } } ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations. public function locations(){} & $location->location()->associate($request->location()); and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file. Web.php Route::get('/somewhere/{id?}, function(){ //do something })->name('test'); Blade route('test', ['id' => $id]); Controller Method public function store(Request $request, $id) //Adding the query parameter for id passed in Route. { $location = new Reservation; $location->name = $request->get('name'); $location->type = $request->get('type'); $location->location()->associate($id); $location->save(); return redirect('/location'); }
How upload file PDF in Laravel Using Vue
I wanna get file pdf document from View use Vue to Laravel. But it still bug. Can help me what is wrong with my code? This is my Blade <template> <form class="form" files="true" method="post" #submit.prevent="onSubmit" enctype="multipart/form-data"> <div class="form-group"> <label>File SK <input type="file" multiple class="form-control-file" name="fileSk" id="fileSk" ref="fileSk" #change="fileSkUpload()"/> </label> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </template> This is my Vue Code for getting file fileSkUpload(event) { let files = event.target.files; if (files.length) this.fileSk = files[0]; }, onSubmit() { let data = new FormData(); data.append('fileSk', this.fileSK); data.append('_method', 'put'); // add this axios.post('/psu/list/store', { data: this.data, }).then(response => { this.data = '' }).catch(error => { if (error.response.status === 422) { this.errors = error.response.data.errors || {}; } }); }, This is my Controller public function store(Request $request) { $dokumen = new Dokumen(); $psu = new Psu(); $fileSk = $request->file('fileSk'); $data = $request->input('fileSk'); $extension = $fileSk->getClientOriginalExtension(); Storage::disk('uploads')->put($fileSk->getFileName() . '.' . $extension, File::get($file)); $dokumen->file_image_dokumen = $fileSk->getFileName() . '.' . $extension; $dokumen->save(); } I got this Error: "Call to a member function getClientOriginalExtension() on null" Error
In your controller you haven't initialised the $file variable. Instead of using the Storage facade to store the file you can just use the Request itself: $fileSk->storeAs('', $fileSk->getFileName() . '.' . $extension, 'uploads'); Storing uploaded files You seem to have a few of issues in your JS code. 1. Don't include the parentheses in #change="fileSkUpload()" as this will cause the event not to be passed to the method: #change="fileSkUpload" alternatively you will have to pass the event yourself: #change="fileSkUpload($event)" $event docs 2. I noticed that in your fileSkUpload method you're referencing this.fileSk but in your onSubmit method you're referencing this.fileSK (capitalised K) - these should be the same. 3. You don't need to wrap the FormData in a object. Change your axios call to just be: axios.post('/psu/list/store', data) .then(response => { this.data = '' }).catch(error => { if (error.response.status === 422) { this.errors = error.response.data.errors || {}; } });
codeigniter get returned data variable from model in controller and use it in conditional statement
what is wrong with my search implementation, here what i wish to achieve. view page(form) -> controller(form data variable) -> model(query database and pass to controller) if there's a result return TRUE else return FALSE -> controller(get data from model) if true display data in table else if FALSE display a no results returned message. here are my pages: view: <form action="<?php echo site_url('retrieve')?>" method="post"> <input type="text" name="id"> .... </form> model: public function retrieve($id) { $search = "SELECT * FROM table"; $result = $this->db->conn_id->prepare($search); $result->execute(); if($result->rowCount()>0){ return $query_result = $result->fetchAll(PDO::FETCH_ASSOC); } } controller: public function retrieve_info() { $id = $this->input->post('id'), $this->load->model('search_model'); $this->search_model->retrieve($id); $data['query_result'] = $this->search_model->retrieve($id); $this->load->view('display',$data); }
First the form action is linking to the retrieve function in the controller. However, from your example there is no retrieve function in your controller, only in your model. view: <form action="<?php echo site_url('retrieve')?>" method="post"> <input type="text" name="id"> .... </form> model: public function retrieve($id) { $search = "SELECT * FROM table"; $result = $this->db->conn_id->prepare($search); $result->execute(); if($result->rowCount()>0){ return $query_result = $result->fetchAll(PDO::FETCH_ASSOC); } } controller: public function retrieve() { if($_POST){ $id = $this->input->post('id'), $this->load->model('search_model'); $data['query_result'] = $this->search_model->retrieve($id); $this->load->view('display',$data); }else { //form failed to submit via post } }