Gabotronix

Experience

6,620

0 Best Reply Awards

  • Member Since 3 Months Ago
  • 29 Lessons Completed
  • 0 Favorites

19th July, 2018

Gabotronix left a reply on Getting Mimes Validation Fail When Not Uploading Optional File With AJAX • 14 hours ago

Will report back once I get home, thx

Gabotronix left a reply on Getting Mimes Validation Fail When Not Uploading Optional File With AJAX • 15 hours ago

Ok so I added nullable to my FormRequest:

public function rules()
    {
        return [
            
            'body' => 'required|string|min:5',
            
            'file' => 'nullable|mimes:doc,pdf,docx,zip,odt,jpeg,bmp,png,jpg,svg|max:2000'
        ];
    }

I also made quite a few changes to my controller method:

public function contactar_reportar_bug(BugReport $request)
    {
        
        $bug = new Bug();
        $bug->body = $request->body;
        $bug->save();
        
        
        if ($request->has('file')) {
            $uploadFile = $request->file('file');
            $mimetype = $uploadFile->getMimeType();
            $filename = str_random(6).'.'.$uploadFile->extension();
            $uploadFile->storeAs('uploads', $filename);
        }
        
        $sender_mail = config('globals.admin_mail');
        
        $destination_mail = config('globals.admin_mail');
        
        $client_phone = config('globals.client_phone');
        
        $body = $request->body;
        
        $restaurant = Globals::where('name' , 'Nombre del restaurante')->pluck('value');
        
        $subject = 'Nuevo reporte de bug en '.$restaurant;
        
        
        
        Mail::to($destination_mail)->send(new BugReportMail($body, $uploadFile, $filename, $mimetype, $subject, $restaurant, $client_phone, $sender_mail));
        
        return response()->json([
        
            'success' => 'Reporte de bug enviado',
            'bug' => $bug,

        ]);
    }

But I'm still getting the same mime related error message

Gabotronix left a reply on Getting Mimes Validation Fail When Not Uploading Optional File With AJAX • 16 hours ago

Oh, so there's no way to attach a file to mail without saving it in storage then?

Gabotronix left a reply on "Integrity Constraint Violation: 1048 Column 'morning' Cannot Be Null" When Updating Optional Values • 18 hours ago

ohh I get it, is the ->input needed or I can just do $request->morning??

Gabotronix left a reply on "Integrity Constraint Violation: 1048 Column 'morning' Cannot Be Null" When Updating Optional Values • 18 hours ago

$schedule->morning = ''; didn't work so I guess I'll add ->nullable() to migration

But sure there has to be a better way to handle this

Gabotronix left a reply on Getting Mimes Validation Fail When Not Uploading Optional File With AJAX • 18 hours ago

Well I'm not saving the file in the app, I just want to attach it to a mail

Gabotronix started a new conversation "Integrity Constraint Violation: 1048 Column 'morning' Cannot Be Null" When Updating Optional Values • 19 hours ago

Hi, In the admin panel I'm trying to make the damin can update the values for morning and night schedules, however he doesn't have to update both.

Sadly, when leave one of the inputs blank it gives me error with the following message : Integrity constraint violation: 1048 Column 'morning' cannot be null, pretty self explanaroey.

This is my blade template form:

<div class="modal_overlay_maincontainer closeable form_update_modal" data-link="schedules">
    <form id="edit_general_form" class="modal_container" >
        <i class="close fa fa-times-circle" title="Cerrar" ></i>
        <h2 class="modal_title">Editar horario de {{ config('globals.web_name') }}</h2>
        <div class="horizontal_gradient_line" style="align-self:center; margin:10px 0px;"></div>
        <div class="modal_body_check_container">
            <span class="modal_body_options_title old_name">Antiguo valor mañama:</span>
            <span class="modal_body_options_title form_old_value_morning"></span>
        </div>
        <div class="modal_body_check_container">
            <span class="modal_body_options_title old_name">Antiguo valor tarde:</span>
            <span class="modal_body_options_title form_old_value_night"></span>
        </div>
        <input id="schedules_morning" class="modal_input" type="text" placeholder="Horas de apertura por la mañana">
        <input id="schedules_night" class="modal_input" type="text" placeholder="Horas de apertura por la tarde">
        <div class="form_valid_container"></div>
        <div class="form_error_container"></div>
        <div class="horizontal_gradient_line" style="align-self:center; margin:10px 0px;"></div>
        <div class="modal_footer_container">
            <button class="modal_footer_add_button form_update_button" type="button" data-link="schedules" data-id="" data-day="" data-morning="" data-night="" title="Guardar cambios">Guardar</button>
            <button class="modal_footer_reset_button form_reset_button" type="button" title="Resetear los campos">Reset</button>
        </div>
    </form>
</div>

My AJAX call to resource controller (I'm sending scrf token so don't worry about that):

$.ajax({
            

                
                async: true,
                cache: false,
                url: 'schedules/' + id,
                type: 'PUT',
                data: 
                {
                    'id' : id,
                    'morning': morning,
                    'night': night
            
                },
                dataType: 'JSON',
                //processData: false,
                //contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
            });

Controller updating method (here I use has() on request variable so I don't know why I'm getting the integruty constraint error really?):

public function update(Request $request , $id)
    {
        $schedule = Schedule::findOrFail($id);
        
        if($request->has('morning')){
            $schedule->morning = $request->morning;
        }
        
        if($request->has('night')){
            $schedule->night = $request->night;
        }

        $schedule->save();
        
        return response()->json([
        
            'schedule' => $schedule,
            'success' => 'Horario actualizado correctamente',
        ]);
    }

Gabotronix started a new conversation Getting Mimes Validation Fail When Not Uploading Optional File With AJAX • 19 hours ago

Hi, I'm trying to make a bug report system where the user sends a body of text and OPTIONALLY he can upload a file (image, doc...) along with the text to be sent to my mail inbox.

However, when I only send text I get this error:

"The file must be a file of type: doc, pdf, docx, zip, odt, jpeg, bmp, png, jpg, svg."

how can I fix this, also when I upload a file along with text the mail is sent all right but the attached file is only 1kb, always.

Jquery code:

var formData = new FormData();
        formData.append('body', $('#bug_body').val());
        formData.append('file', $('#bug_file').prop('files')[0]);
        
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({
            
            async: true,
            url: '/contactar-mail-bug',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false, 
            dataType: 'JSON',
            
            success: function (data) { 
                $('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                form.trigger("reset");
                console.log(data.success);
            },
            
            error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
                
                $.each(errors , function(){
                    $('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                }); 
            }

        });

Method for sending email:

public function contactar_reportar_bug(BugReport $request)
    {
        $sender_mail = config('globals.admin_mail');//mail sender, in this case it's me
        
        $destination_mail = config('globals.admin_mail');//mail receiver, in this case it's me too
        
        $client_phone = config('globals.client_phone');
        
        $body = $request->body;//bug report mail message
        
        $file = $request->file('file');//bug report screencap or doc
        
        $file_name = $file->getClientOriginalName();//outputs Laravel DOC.odt
        
        $mime_type = $file->getMimeType();//outputs application/
        
        $file_extension = $file->guessExtension();//outputs .odt
        
        $restaurant = Globals::where('name' , 'Nombre del restaurante')->pluck('value');//outputs web_name, used in the mail subject
        
        $subject = "Nuevo reporte de bug en $restaurant";//subject of the mail
        
        
        
        
        $bug = new Bug();
        $bug->body = $request->body;
        $bug->save();
        
        
        
        Mail::to($destination_mail)->send(new BugReportMail($body, $file, $subject, $restaurant, $client_phone, $sender_mail, $file_name, $mime_type));
        
        return response()->json([
        
            'success' => 'Reporte de bug enviado',
            'bug' => $bug,

        ]);
    }

Bug Report form request (notice how only the body of the message is required):

public function rules()
    {
        return [
            
            'body' => 'required|string|min:5',
            
            'file' => 'mimes:doc,pdf,docx,zip,odt,jpeg,bmp,png,jpg,svg|max:2000'
        ];
    }

18th July, 2018

Gabotronix started a new conversation MethodNotAllowedHttpException Error With No Message After AJAX Call To Resource Controller • 1 day ago

I'm updating the value of some models in a database but when I hit submit I get the following error:

message: "", exception: "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException", file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php", line: 255

This is my JQuery code:

var formData = new FormData();
            formData.append('id', $(this).attr("data-id"));
            formData.append('first', $('#schedules_morning').val());
            formData.append('second', $('#schedules_night').val());
            
            $.ajax({
            

                
                async: true,
                cache: false,
                url: '/schedules',
                type: 'PUT',
                data: 
                {
                formData
                },
                dataType: 'JSON',
                processData: false,
                contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
            });

I'm sending the request to a resource controller route:

Route::resource('/schedules','ScheduleController');
public function update(Request $request)
    {
        $schedule = Schedule::findOrFail($id);
        $schedule->morning = $request->morning;
        $schedule->night = $request->night;
        $schedule->save();
        
        return response()->json([
        
            'schedule' => $schedule,
            'success' => 'Horario actualizado correctamente',
        ]);
    }

16th July, 2018

Gabotronix started a new conversation Issue With Simple Jquery Slider • 3 days ago

So as a means of learning jquery I'm making my own slider where each image swipes to the left creating a nice effect, this is beacuse I change the left property of the absolutely positioned images container.

However I fail to make it move, what I do is capture the width of each image in the slider and mov the container accordingly.

My code:

$(document).ready(function() {
  var interval = 2000; //will move to left 450px each X seconds
  var sliders = $('.slider_image'); //counts number of sliders
  var image_width = $('.slider_image').width();
  var index = 0;
  var show_index = 0;
  var scrolledPx = 0;

  setInterval(function() {

    if (scrolledPx >= image_width * sliders.length - 1) {

      $('.sliders_container').animate({
        'left': '0px'
      }, 2000);
      scrolledPx = 0;

    } else {

      $('.sliders_container').animate({
        'left': '-= ' + image_width + ''
      }, 1000);
      scrolledPx += image_width;
    }

  }, interval);
});
/*SECTION SLIDER MARG START*/

.section_slider_marg_maincontainer {
  width: 100%;
  height: 275px;
  outline: 2px solid white;
  position: relative;
  overflow: hidden;
}

.section_slider_marg_items_container {
  width: auto;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  display: flex;
}

.section_slider_marg_item {
  height: 100%;
  width: 450px;
  outline: 2px solid red;
  background-size: cover;
}


/*SECTION SLIDER MARG END*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="section_slider_marg_maincontainer" style="">
  <div class="section_slider_marg_items_container sliders_container" style="">
    <div class="section_slider_marg_item slider_image" style="background-image:url('img/Res1.jpg');">1</div>
    <div class="section_slider_marg_item slider_image" style="background-image:url('img/Res1.jpg');">2</div>
    <div class="section_slider_marg_item slider_image" style="background-image:url('img/Res1.jpg');">3</div>
    <div class="section_slider_marg_item slider_image" style="background-image:url('img/Res1.jpg');">4</div>
    <div class="section_slider_marg_item slider_image" style="background-image:url('img/Res1.jpg');">5</div>
    <div class="section_slider_marg_item slider_image" style="background-image:url('img/Res1.jpg');">6</div>
  </div>
</section>

11th July, 2018

Gabotronix started a new conversation Sharing Data With All Views With BaseController • 1 week ago

Since I was having troubles with view composers I decided to take a new approach to the issue, by creating a BaseController that extends laravel's own controller and using the controller's contruct methods.

Like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use app\Globals;
use Illuminate\Support\Facades\View;

class BaseController extends Controller
{
    public function __construct()
    {
      
        $globals = Globals::all();
        
        $web_name = $globals->where('name', 'Nombre del restaurante')->first();
        $web_description = $globals->where('name', 'Descripcion en google del restaurante')->first();
        $restaurant_bio = $globals->where('name', 'Biografia del restaurante')->first();
        $booking_phone = $globals->where('name', 'Télefono de reserva')->first();
        $client_mail = $globals->where('name', 'Email de contacto')->first();
        $full_address = $globals->where('name', 'Dirección del restaurante')->first();
        $city_zip_address = $globals->where('name', 'Código postal y ciudad')->first();
        
        $config = compact('web_name', 'web_description', 'restaurant_bio', 'booking_phone', 'client_mail', 'full_address', 'city_zip_address');

        View::share('globals', $globals);
    }
}

Sadly I'm getting the following error:

Undefined variable: config (View: C:\xampp\htdocs\Restaurante1\resources\views\inicio\index.blade.php)

Gabotronix started a new conversation Sharing Data To All Views With View Composers • 1 week ago

Hi, after reading the documentation on View Composers I'm a bit confused, so I added the view service provider to the providers array in config\app.

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,
            app\Providers\ComposerServiceProvider::class,

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

    ],

This is my ComposerServiceProvider class:

Gabotronix left a reply on Issue When Sending AJAX POST Request When Checkbox State Changes • 1 week ago

I fixed this changing

formData.append('isVisible', $('.entry_checkbox[data-link=' + linked_entry + ']').is(':checked') ? 1 : 0);

to this:

formData.append('isVisible', $(this).is(':checked') ? 1 : 0);

Gabotronix started a new conversation Trying To Access Value Inside Array In View • 1 week ago

So I'm trying to access the value of a few pair of key -> values inside an array I create and pass to the view called config, I'd like to access to them like this : {{ $config->web_name['value'] }} or {{ $config->$web_name['value'] }} but both are returning errors.

This is how I pass the data to my view:

public function inicio()
    {
        
        $pageInfo = 
        [
            'page_title'      => 'Inicio',
            'menu_active'     => 'Inicio',
            'submenu_active' => '',
        ];
        
        $globals = Globals::all();
        
        $web_name = $globals->where('name', 'Nombre del restaurante')->first();
        $web_description = $globals->where('name', 'Descripcion en google del restaurante')->first();
        $restaurant_bio = $globals->where('name', 'Biografia del restaurante')->first();
        $booking_phone = $globals->where('name', 'Télefono de reserva')->first();
        $client_mail = $globals->where('name', 'Email de contacto')->first();
        $full_address = $globals->where('name', 'Dirección del restaurante')->first();
        $city_zip_address = $globals->where('name', 'Código postal y ciudad')->first();
        
        $config = compact('web_name', 'web_description');
        
        $sliders = Slider::all();

        
        return view('inicio.index', compact('pageInfo', 'config', 'sliders', 'web_name'));
    }

Gabotronix left a reply on Can't Access Uploaded Images In The Browser • 1 week ago

That worked perfectly, thanks Cronix

Gabotronix left a reply on Can't Access Uploaded Images In The Browser • 1 week ago

After checking http://127.0.0.1:8000/storage/uploads/jDPEGL.png I can see the image perfectly in the browser

Gabotronix left a reply on Issue When Sending AJAX POST Request When Checkbox State Changes • 1 week ago

Ok after some debuggin the parameter isVisible always returns as 1:

public function updateVisibility(Request $request)
    {
        dd($request->all());
        
        
        
        $id = $request->id;
        $slider = Slider::findOrFail($id);
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        $visibility = $slider->isVisible;
        
        return response()->json([
        
            'success' => 'Diapositiva actualizada correctamente',
            'slider' => $slider,
            'visibility' => $visibility,
        ]);
    }

dd output:

array:2 [
  "id" => "1"
  "isVisible" => "1"
]

It will return the id and always a value of 1

Gabotronix left a reply on Accesing Variable Value From Model And Showing It In Blade • 1 week ago

I have many more variables in my globals page, not all of them are CRUDeable .

Gabotronix started a new conversation Issue When Sending AJAX POST Request When Checkbox State Changes • 1 week ago

Hi, for the admin panel I'm building I can make posts appear as visible or invisible if you check or uncheck a checkbox, when the checkbox is clicked a POST request is send to the /posts-update-visibility method which updates the isVisble property of the Post model.

For some reason the isVisible is not being updated and isVisible ALWAYS returns 1 no matter what.

First the posts are retrieved from database with AJAX GET call:

$.ajax({

                    async: true,
                    url: '/posts',
                    type: 'GET',
                    dataType: 'JSON',
             
                    success: function (data) { 
                            
                        $('.row[data-link=' + linked_entry + ']').remove();
                    
                        $.each(data.posts, function (index, item) {
                    
                            var posts_row = '<tr class="row" data-link="posts">';
                            posts_row += '<td>' + item.title + '</td>';
                            posts_row += '<td>' + item.body + '</td>';
                            posts_row += '<td><div style="width:110px; height:60px; background-image:url(' + item.image + '); background-size:cover;"></div></td>';
                            posts_row += '<td style="text-align:center;"><input type="checkbox" class="entry_checkbox" data-link="posts" data-id="' + item.id + '" data-isVisible="' + item.isVisible + '" name="isVisible" '+(item.isVisible ? 'checked' : '')+'></td>';
                            posts_row += '</tr>';
    
                            $('.entry_table_container[data-link=' + linked_entry + ']').append(posts_row);
                        });
                                
                          
                    },
            
                    error: function (data){
                        var errors = data.responseJSON;
                        console.log(errors);
                    }
                
                });

Then when checkbox state is detected I send POST request:

$(document).on('change', '.entry_checkbox', function() {
        console.log('Checkbox state changed');
        
        linked_entry = $(this).attr("data-link");
        console.log(linked_entry);
        
        
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        

        switch(linked_entry) {
            
            case "posts":
            
            
                var formData = new FormData();
                formData.append('id', $(this).attr("data-id"));
                formData.append('isVisible', $('.entry_checkbox[data-link=' + linked_entry + ']').is(':checked') ? 1 : 0);
            
                $.ajax({
        
                    async: true,
                    cache: false,
                    url: '/posts-update-visibility',
                    type: 'POST',
                    data: formData,
                    dataType: 'JSON',
                    processData: false,
                    contentType: false,
            
                    success: function (data) { 
                        console.log(data.success);
                        console.log(data.visibility);
                    },
            
                    error: function (data){
                        var errors = data.responseJSON;
                        console.log(errors);
                    }
                });

            break;
                    
            default: 
        }
    });

My controller method where I update isVisible (it doesn't actually updates anything and always returns 1, always, both $visibility and isVisible).

public function updateVisibility(Request $request)
    {
        $id = $request->id;
        $post = Post::findOrFail($id);
        $post->isVisible = $request->isVisible;
        $post->save();
        
        $visibility = $post->isVisible;
        
        return response()->json([
        
            'success' => 'Publicación actualizada correctamente',
            'post' => $post,
            'visibility' => $visibility,
        ]);
    }

This is js console feed: Checkbox state changed posts Publicación actualizada correctamente 1

post    {…}
id  2
title   Titulo del segundo post
body    Descripcion del segundo post
image   img/posts/2.jpg
isVisible   1
created_at  null
updated_at  null
visibility  1

10th July, 2018

Gabotronix left a reply on Accesing Variable Value From Model And Showing It In Blade • 1 week ago

It's beacuse I persorm CRUD operations on the global variables, so the value changes

Gabotronix started a new conversation Accesing Variable Value From Model And Showing It In Blade • 1 week ago

Hi, for my admin panel project I created a table called globals, with fields name and value.

This is the migration of globals table:

//CREATE GLOBALS TABLE
        Schema::create('globals', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('value');
            $table->timestamps();
        });
        //FILL GLOBALS TABLE WITH DUMMY POSTS
        DB::table('globals')->insert([
            'name' => 'Nombre del restaurante',
            'value' => config('globals.web_name'),
        ]);
        DB::table('globals')->insert([
            'name' => 'Descripcion en google del restaurante',
            'value' => config('globals.web_description'),
        ]);
        DB::table('globals')->insert([
            'name' => 'Biografia del restaurante',
            'value' => config('globals.restaurant_bio'),
        ]);
        DB::table('globals')->insert([
            'name' => 'Télefono de reserva',
            'value' => config('globals.booking_phone'),
        ]);
        DB::table('globals')->insert([
            'name' => 'Email de contacto',
            'value' => config('globals.client_mail'),
        ]);
        DB::table('globals')->insert([
            'name' => 'Dirección del restaurante',
            'value' => config('globals.full_address'),
        ]);
        DB::table('globals')->insert([
            'name' => 'Código postal y ciudad',
            'value' => config('globals.city_zip_address'),
        ]);

I want to have access to my variables in my blade templates, but I don't know how to access the value field referencing the name field, something like $globals->name->value??

This is how I retrieve globals and post them into the view:

public function inicio()
    {
        
        $pageInfo = 
        [
            'page_title'      => 'Inicio',
            'menu_active'     => 'Inicio',
            'submenu_active' => '',
        ];
        
        $globals = Globals::all();
        $sliders = Slider::all();

        
        return view('inicio.index', compact('pageInfo', $globals, $sliders));
    }

I know about the {{ }} echo thing

Please give me some advice on this

Gabotronix started a new conversation Can't Access Uploaded Images In The Browser • 1 week ago

Hi, I'm making an admin panel wich lets you upload and visualize each entry you create, I'm uploading images via AJAX into the following folder:

C:\xampp\htdocs\Restaurante1\storage\app\public\uploads

Problem is when I append the data into my table the images are not visible since they are not in the public directory, this is what they look like after I print the values with JQuery:

 background-image:url(storage/app/public/uploads/jDPEGL.png); 

I tried making a symbolic link with php artisan storage:link but it's not working.

Any idea how I can fix this?

This is the controller methos wher I store the entries:

 public function store(StoreSlider $request)
    {
        
        $uploadFile = $request->file('image');
        
        //generate random filename and append original extension (eg: asddasada.jpg, asddasada.png)
        $filename = str_random(6).'.'.$uploadFile->extension();

        // storing path (Change it to your desired path in public folder)
        //$path = 'img/uploads/';

        // Move file to public filder
        $uploadFile->storeAs('uploads', $filename);
        
        
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = 'storage/app/public/uploads/'.$filename; // So that you can access image by url($slider->image);
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json([
        
            'success' => 'Diapositiva guardada correctamente',
            'slider' => $slider,
        ]);
    }

and my filesystems config file:

eturn [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DRIVER', 'public'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

];

9th July, 2018

Gabotronix started a new conversation Issue When Storing To Database And Sending Bulletin By Mail • 1 week ago

Hi, I'm using JQuery and AJAX to store a simple news bulletin (title and body), after sending the data the bulletin is send to be first stored via AJAX POST, then the bulletin info is sent back to be sent again via POST to the same resource controller.

My routes:

Route::post('/bulletins', '[email protected]');

Route::resource('/bulletins','BulletinController');

This is my JQuery function, here is where the two AJAX calls are made (to store bulletin, and then to send the markdown mail.

$('.form_store_and_send').click(function(e){
        e.preventDefault();
        
        var linked_entry = $(this).attr("data-link");
        var form = $(this).closest('form');
        
        
        
        
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        

        switch(linked_entry) {
            
            case "subs":
            
                console.log('store and send clicked');
                
                var formData = new FormData();
                formData.append('title', $('#subs_title').val());
                formData.append('body', $('#subs_title').val());

                
                $.ajax({

                    async: true,
                    url: '/bulletins',
                    type: 'POST',
                    data: formData,
                    dataType: 'JSON',
                    processData: false,
                    contentType: false,
            
                    success: function (data) { 
                
                        $.ajax({

                            async: true,
                            url: '/bulletins',
                            type: 'POST',
                            data: formData,
                            dataType: 'JSON',
                            processData: false,
                            contentType: false,
            
                            success: function (data) { 
                                 
                                 
                                console.log(data.subs);
                                console.log('Bulletin saved, preparing to send');
                                
                                $.ajax({

                                    async: true,
                                    url: '/bulletins',
                                    type: 'POST',
                                    data: formData,
                                    dataType: 'JSON',
                                    processData: false,
                                    contentType: false,
            
                                    success: function (data) { 
                
                                         
                                        $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                                        form.trigger("reset");
                                        console.log('Mail sent');
                                },
            
                                    error: function (data){
                                    var errors = data.responseJSON;
                                    console.log(errors);
                                    console.log('failed to send mail');
                
                                    $.each(errors , function(){
                                        $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                                    }); 
                                    }
                                });
                                
                            },
            
                            error: function (data){
                                var errors = data.responseJSON;
                                console.log(errors);
                
                                $.each(errors , function(){
                                    $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                                }); 
                            }
                        });
                        

                    },
            
                    error: function (data){
                        var errors = data.responseJSON;
                        console.log(errors);
                
                        $.each(errors , function(){
                            $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                        }); 
                    }
                
                
                });

            break;
            
            default:   
        }   
    });

BulletinController, this is where the code for storing and sending the mail is, this is a resource controller but there's another method I added, sendBulletin().

<?php

namespace App\Http\Controllers;

use App\Bulletin;
use Illuminate\Http\Request;
use App\Http\Requests\StoreBulletin;
use Mail;
use App\Sub;

class BulletinController extends Controller
{




    public function sendBulletin(Request $request)
    {
        
        $bulletin = $request->bulletin;
        
        $sender_mail = config('globals.admin_mail');
        
        $destination_mail = config('globals.client_mail');
        
        $body = $request->bulletin->body;
        
        $title = $request->bulletin->title;
        
        $restaurant = config('globals.web_name');
        
        $subject = "Opinión anónima de $restaurant";
        
        $subs = $request->subs;
        
        
        Mail::to($destination_mail)->send(new SimpleBulletinMail($body, $title, $restaurant, $subject, $sender_mail));
        
        
        return response()->json([
        
            'success' => 'Boletin enviado y guardado correctamente',
            'bulletin' => $bulletin,
        ]);
    }
    
    
    
    
    public function index()
    {
        $bulletins = Bulletin::all();
        
        return response()->json([
        
            'success' => 'Todos los boletines recogidos',
            'bulletins' => $bulletins,
        ]);
    }


    
    
    public function create()
    {
        //
    }


    
    
    public function store(StoreBulletin $request)
    {
        $bulletin = new Bulletin();
        $bulletin->title = $request->title;
        $bulletin->body = $request->body;
        $bulletin->save();
        
        $subs = new Sub();
        $subs = Sub::all()->pluck('email');
        
        
        return response()->json([
        
            'success' => 'Boletín guardado correctamente',
            'bulletin' => $bulletin,
            'subs' => $subs,
        ]);
    }

ISSUE: Now for the issue, instead of being saved and send via mail, the bulletin (title and body) is saved into database (store method in resource controller) no more than three times, sendBulletin POST request is not being hit for some reason.

https://i.imgur.com/zzpdgah.png

My console feed:

store and send clicked restaurante1_admin_panel.js:561:8
Array [ "[email protected]" ]
restaurante1_admin_panel.js:593:9
Bulletin saved, preparing to send restaurante1_admin_panel.js:594:9
Mail sent

Gabotronix started a new conversation "Impossible To Create The Root Directory " Error When Uploading File Into Public Folder • 1 week ago

I'm trying to store a file via AJAX to public folder in laravel, however when I submit the form I get the following message:

" message: "Impossible to create the root directory "C:\xampp\htdocs\Restaurante1\storage\app\C:/xampp/htdocs/Restaurante1/public/img".", exception: "League\Flysystem\Exception", file: "C:\xampp\htdocs\Restaurante1\vendor\league\flysystem\src\Adapter\Local.php"

I'm trying to store the file into the following folder inside public directory: public > img >uploads

My controller method for storing new sliders:

public function store(StoreSlider $request)
    {
        
        $uploadFile = $request->file('image');
        
        //generate random filename and append original extension (eg: asddasada.jpg, asddasada.png)
        $filename = str_random(6).'.'.$uploadFile->extension();

        // storing path (Change it to your desired path in public folder)
        $path = 'img/uploads/';

        // Move file to public filder
        $uploadFile->storeAs(public_path($path), $filename);
        
        
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = $path.'/'.$filename; // So that you can access image by url($slider->image);
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json([
        
            'success' => 'Diapositiva guardada correctamente',
            'slider' => $slider,
        ]);
    }

Gabotronix left a reply on Models Saved Into Database Appearing As [object Object] • 1 week ago

No worries, I was not retrieving the actual value of the inputs, I added .val() and now it works

Gabotronix started a new conversation Models Saved Into Database Appearing As [object Object] • 1 week ago

I'm using a form to store a Bulletin model, I retrieve title and body fields from a form using formData object since this has proven for me to be the best way to store info into dtabase using AJAX.

However after checking phpmyAdmin the fields I saved appear as [object Object] instead of their input values.

This is my JQuery code:

console.log('new bulletin button clicked');
                
                var formData = new FormData();
                formData.append('title', $('#subs_title'));
                formData.append('body', $('#subs_body'));
            
                console.log('new bulletin button clicked');

                
                $.ajax({

                async: true,
                url: '/bulletins',
                type: 'POST',
                data: formData,
                dataType: 'JSON',
                processData: false,
                contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success, data.errors);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
                });

This is my view:

<div class="modal_overlay_maincontainer closeable form_store_modal" data-link="subs">
    <form id="new_sub_form" class="modal_container" >
        <i class="close fa fa-times-circle" title="Cerrar"></i>
        <h2 class="modal_title">Nuevo boletín</h2>
        <div class="modal_body_container">
            <input id="subs_title" class="modal_input" type="text" name="subs_title" placeholder="Titulo del boletín" required>
            <textarea id="subs_body" class="modal_input_textarea" name="subs_body" placeholder="Contenido del boletín" required></textarea>
        </div>
        <div class="form_valid_container"></div>
        <div class="form_error_container"></div>
        <div class="modal_footer_container">
            <button class="modal_footer_add_button sendBulletins" type="button" data-link="subs" title="Enviar a todos tus subscriptores" style="margin-left:auto; background-color:#82C91E;">Enviar y guardar</button>
            <button class="modal_footer_add_button form_store_button" type="button" data-link="subs" title="Guardar el boletín para enviar más tarde" style="margin:0px 10px;">Guardar</button>
            <button class="modal_footer_reset_button form_reset_button" type="button" title="Resetear los campos">Reset</button>
        </div>
    </form>
</div>

my controller store method:

public function store(StoreBulletin $request)
    {
        $bulletin = new Bulletin();
        $bulletin->title = $request->title;
        $bulletin->body = $request->body;
        $bulletin->save();
        
        
        return response()->json([
        
            'success' => 'Boletín guardado correctamente',
            'bulletin' => $bulletin,
        ]);
    }

Gabotronix left a reply on Failing To Upload File With AJAX "Call To A Member Function HashName() On Null" • 1 week ago

Ok, I think I fixed the issue by replacing

formData.append('image', form.closest($("input[name='slider_image']").prop('files')[0]));

by

formData.append('image', $('#slider_image').prop('files')[0]);

My controller method for storing into database now ookis like this:

public function store(StoreSlider $request)
    {
        
        $uploadFile = $request->file('image');
        
        //generate random filename and append original extension (eg: asddasada.jpg, asddasada.png)
        $filename = str_random(6).'.'.$uploadFile->extension();

        // storing path (Change it to your desired path in public folder)
        $path = 'img/uploads/';

        // Move file to public filder
        $uploadFile->storeAs(public_path($path), $filename);
        
        
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = $path.'/'.$filename; // So that you can access image by url($slider->image);
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json($slider);
    }

However when I submit I get the following error:

message: "Impossible to create the root directory \"C:\xampp\htdocs\Restaurante1\storage\app\C:/xampp/htdocs/Restaurante1/public/img/uploads\".", exception: "League\Flysystem\Exception", file: "C:\xampp\htdocs\Restaurante1\vendor\league\flysystem\src\Adapter\Local.php"

This is weird since I already created a folder named uploads inside img in public folder

C:\xampp\htdocs\Restaurante1\public\img\uploads

Gabotronix started a new conversation Failing To Upload File With AJAX "Call To A Member Function HashName() On Null" • 1 week ago

I'm trying to upload an image via AJAX call, first I was getting mime type validation errors, after removing the validation rules I get this:

message: "Call to a member function hashName() on null", exception: "Symfony\Component\Debug\Exception\FatalThrowableError", file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Filesystem\FilesystemAdapter.php", line: 193, trace: (56)

I'm fairly sure I'm failing at retrieving the file from my input file type inside my form, this is weird as I set the enctype correctly.

My form where I think the error resides:

<div class="modal_overlay_maincontainer closeable form_store_modal" data-link="sliders">
    <form id="new_slider_form" class="modal_container" enctype='multipart/form-data'>
        <i class="close fa fa-times-circle" title="Cerrar"></i>
        <h2 class="modal_title">Nueva Diapositivas</h2>
        <div class="modal_body_container">
            <div class="modal_body_check_container">
                <span class="modal_body_options_title">Visible</span>
                <input class="modal_body_check" name="isVisible" type="checkbox"  title="La diapositiva se subirá al pasador de diapositivas" required>
            </div>
            <div class="modal_body_check_container">
                <span class="modal_body_options_title">Imagen</span>
                <input type="file" name="image" required>
            </div>
            <input class="modal_input" type="text" name="title" placeholder="Titulo de la diapositiva" required>
            <textarea class="modal_input_textarea" name="body" placeholder="Contenido de la diapositiva" required></textarea>
        </div>
        <div class="modal_footer_container">
            <button class="modal_footer_add_button form_store_button" type="button" data-link="sliders" title="Crear nueva entrada">Crear</button>
            <button class="modal_footer_reset_button form_reset_button" type="button" title="Resetear los campos">Reset</button>
        </div>
    </form>
</div>

And my JQuery code:

$('.form_store_button').click(function(){
        
        var linked_entry = $(this).attr("data-link");
        var form = $(this).closest('form');
        
        
        
        
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        

        switch(linked_entry) {
            
            case "sliders":
            
                console.log('new slider button clicked');
                
                var formData = new FormData();
                formData.append('title', form.closest($("input[name='title']").val()));
                formData.append('body', form.closest($("textarea[name='body']").val()));
                formData.append('image', form.closest($("input[name='image']").prop('files')[0]));
                formData.append('isVisible', form.closest($("input[name='isVisible']").is(':checked') ? 1 : 0));

                
                $.ajax({

                async: true,
                url: '/sliders',
                type: 'POST',
                data: formData,
                dataType: 'JSON',
                processData: false,
                contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success, data.errors);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
                });

            break;
                    
                    

            default:
                        
        }
                
    });

Gabotronix started a new conversation Storing Images In Public Folder Via AJAX POST • 1 week ago

Hi, I'm making an admin panel for a personal project as a means to studying laravel framework, so far I'm loving it!

I came up with a issue where I don't know how to store the uploaded image into my app (I'd like to use public folder instead of other storage despite being less secure), I have my folder called uploads inside public.

This is my AJAX POST call:

$('.form_store_button').click(function(){
        
        var linked_entry = $(this).attr("data-link");
        var form = $(this).closest('form');
        
        
        
        
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        

        switch(linked_entry) {
            
            case "sliders":
            
                console.log('new slider button clicked');
                
                var formData = new FormData();
                formData.append('title', form.closest($("input[name='title']").val()));
                formData.append('body', form.closest($("textarea[name='body']").val()));
                formData.append('image', form.closest($("input[name='image']").prop('files')[0]));
                formData.append('isVisible', form.closest($("input[name='isVisible']").is(':checked') ? 1 : 0));

                
                $.ajax({

                async: true,
                url: '/sliders',
                type: 'POST',
                data: formData,
                dataType: 'JSON',
                processData: false,
                contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success, data.errors);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
                });

            break;
                    
                    

            default:
                        
        }
                
    });

My resource controller:

public function store(StoreSlider $request)
    {
        
        dd($request->all);
        
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = $request->image;
        $slider->image = $request->file('image');
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json($slider);
    }

8th July, 2018

Gabotronix started a new conversation Getting "Invalid Datetime Format" Error When Submitting AJAX Form • 1 week ago

I'm trying to store a new entry into my database but I get the following error when I submit the form:

The error:

message: "SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'on' for column 'isVisible' at row 1 (SQL: insert into `sliders` (`title`, `body`, `image`, `isVisible`, `updated_at`, `created_at`) values (xxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, C:\xampp\tmp\php3E02.tmp, on, 2018-07-08 19:08:18, 2018-07-08 19:08:18))", exception: "Illuminate\Database\QueryException",

This is my jquery AJAX POST call:

$('.form_store_button').click(function(){
        
        var linked_entry = $(this).attr("data-link");
        
        
        
        
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        

        switch(linked_entry) {
            
            case "sliders":
            
                console.log('new slider button clicked');
                
                var formData = new FormData();
                formData.append('title', $("input[name='title']").val());
                formData.append('body', $("textarea[name='body']").val());
                formData.append('image', $("input[name='image']").prop('files')[0]);
                formData.append('isVisible', $("input[name='isVisible']").val());

                
                $.ajax({

                async: true,
                url: '/sliders',
                type: 'POST',
                data: formData,
                dataType: 'JSON',
                processData: false,
                contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success, data.errors);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
                });

            break;
                    
                    

            default:
                        
        }
                
    });

My controller:

public function store(StoreSlider $request)
    {
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = $request->image;
        $slider->image = $request->file('image');
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json($slider);
    }

And the migration where I create sliders table:

Schema::create('sliders', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->nullable();
            $table->string('body')->nullable();
            $table->string('image');
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });

Gabotronix left a reply on Getting Error Exception "array To String Conversion" • 1 week ago

That gives me the error, so it's safe to assume it's the save ing method which throws the exception, it's really werid.

I don't have any event listener neither

Gabotronix left a reply on Getting Error Exception "array To String Conversion" • 1 week ago

This is the outpout:

array:1 [
  "email" => "[email protected]"
]

Gabotronix left a reply on Getting Error Exception "array To String Conversion" • 1 week ago

I added dd like you did and the request got 200 status, this is also the response I'm getting:

array:1 [
  "email" => "[email protected]"
]

Gabotronix left a reply on Getting Error Exception "array To String Conversion" • 1 week ago

Changed it but still getting the same error

Gabotronix started a new conversation Getting Error Exception "array To String Conversion" • 1 week ago

I'm getting the following error thrown when I try to save an email into a database, what I'm trying to do is the classic subscription system.

This is my full error:

exception: "ErrorException"
​
file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Grammar.php"
​
line: 39
​
message: "Array to string conversion"
​
trace: (64) […]
​​
0: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Grammar.php", line: 39, function: "handleError", … }
​​
1: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php", line: 731, function: "wrapTable", … }
​​
2: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php", line: 759, function: "compileInsert", … }
​​
3: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php", line: 2490, function: "compileInsertGetId", … }
​​
4: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php", line: 1283, function: "insertGetId", … }
​​
5: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php", line: 732, function: "__call", … }
​​
6: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php", line: 697, function: "insertAndSetId", … }
​​
7: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php", line: 560, function: "performInsert", … }
​​
8: Object { file: "C:\xampp\htdocs\Restaurante1\app\Http\Controllers\SubscriptionController.php", line: 44, function: "save", … }
​​
9: Object { function: "store", class: "App\Http\Controllers\SubscriptionController", type: "->" }
​​
10: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Controller.php", line: 54, function: "call_user_func_array" }
​​
11: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php", line: 45, function: "callAction", … }
​​
12: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Route.php", line: 212, function: "dispatch", … }
​​
13: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Route.php", line: 169, function: "runController", … }
​​
14: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Router.php", line: 665, function: "run", … }
​​
15: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 30, function: "Illuminate\Routing\{closure}", … }
​​
16: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php", line: 41, function: "Illuminate\Routing\{closure}", … }
​​
17: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
18: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
19: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php", line: 67, function: "Illuminate\Routing\{closure}", … }
​​
20: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
21: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
22: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php", line: 49, function: "Illuminate\Routing\{closure}", … }
​​
23: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
24: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
25: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php", line: 63, function: "Illuminate\Routing\{closure}", … }
​​
26: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
27: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
28: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php", line: 37, function: "Illuminate\Routing\{closure}", … }
​​
29: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
30: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
31: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php", line: 59, function: "Illuminate\Routing\{closure}", … }
​​
32: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
33: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
34: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 104, function: "Illuminate\Routing\{closure}", … }
​​
35: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Router.php", line: 667, function: "then", … }
​​
36: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Router.php", line: 642, function: "runRouteWithinStack", … }
​​
37: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Router.php", line: 608, function: "runRoute", … }
​​
38: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Router.php", line: 597, function: "dispatchToRoute", … }
​​
39: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php", line: 176, function: "dispatch", … }
​​
40: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 30, function: "Illuminate\Foundation\Http\{closure}", … }
​​
41: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\fideloper\proxy\src\TrustProxies.php", line: 57, function: "Illuminate\Routing\{closure}", … }
​​
42: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
43: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
44: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\spatie\laravel-cookie-consent\src\CookieConsentMiddleware.php", line: 21, function: "Illuminate\Routing\{closure}", … }
​​
45: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
46: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
47: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php", line: 31, function: "Illuminate\Routing\{closure}", … }
​​
48: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
49: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
50: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php", line: 31, function: "Illuminate\Routing\{closure}", … }
​​
51: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
52: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
53: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php", line: 27, function: "Illuminate\Routing\{closure}", … }
​​
54: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
55: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
56: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php", line: 51, function: "Illuminate\Routing\{closure}", … }
​​
57: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 151, function: "handle", … }
​​
58: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php", line: 53, function: "Illuminate\Pipeline\{closure}", … }
​​
59: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php", line: 104, function: "Illuminate\Routing\{closure}", … }
​​
60: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php", line: 151, function: "then", … }
​​
61: Object { file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php", line: 116, function: "sendRequestThroughRouter", … }
​​
62: Object { file: "C:\xampp\htdocs\Restaurante1\public\index.php", line: 55, function: "handle", … }
​​
63: Object { file: "C:\xampp\htdocs\Restaurante1\server.php", line: 21, function: "require_once" }
​​
length: 64
​​
<prototype>: Array []
​
<prototype>: Object { … }

This is my JQuery code:

$(document).ready(function(){
    
    
    
    $(".startSubscription").click(function(){
        var form = $(this).closest('form');
        $('.form_error_text').hide();
        $('.form_valid_text').hide();
        console.log('button start subscription clicked');
        
        var emailval=$("input[name='email']").val();
        
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({
            
            async: true,
            cache: false,
            url: '/subscriptions',
            type: 'POST',
            data: 
            {
                
            'email': emailval
            
            },
            dataType: 'JSON',
            
            success: function (data) { 
                $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                form.trigger("reset");
                console.log(data.success);
            },
            
            error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
                
                $.each(errors , function(){
                    $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                }); 
            }

        }); 
    });
    

});

And my controller where I save the email to a database:

public function store(StoreSubbedMail $request)
    {
        $subscription = new Subscription();
        $subscription->email = $request->email;
        $subscription->save();
        
        return response()->json([
        
            'success' => 'Te subscribiste correctamente'
        ]);
    }

7th July, 2018

Gabotronix left a reply on AJAX POST Request Throws "MethodNotAllowedHttpException No Message" Error Right After I Submit It • 1 week ago

I tried with /sub and the request was sent BUT I'm still getting the same exception thrown, after checking network tab it appears there's ANOTHER POST request, this is the one wich is giving me the error for sure.

Problem is I have no idea what is sending that request??

https://i.imgur.com/8itW66M.png

How can I know where that request comes from?

Gabotronix left a reply on AJAX POST Request Throws "MethodNotAllowedHttpException No Message" Error Right After I Submit It • 1 week ago

I updated OP with my view, also just checked the network tab and the POST request is being sent to http://127.0.0.1:8000/ with a status code of 405, it's not being sent to my route... weird

Gabotronix left a reply on AJAX POST Request Throws "MethodNotAllowedHttpException No Message" Error Right After I Submit It • 1 week ago

No, these are all my routes:

Route::get('/', '[email protected]');

Route::get('/nuestra-carta-de-menus', '[email protected]');

Route::get('/localizacion', '[email protected]');

Route::get('/horario-de-apertura', '[email protected]');

Route::get('/contacta-con-nosotros', '[email protected]');

Route::get('/contactar/hacer-una-reserva', '[email protected]');

Route::get('/contactar/trabaja-con-nosotros', '[email protected]');

Route::get('/opiniones-de-nuestros-clientes', '[email protected]');

Route::get('/diseños', '[email protected]ños');

Route::get('/panel-de-administrador', '[email protected]');//->middleware('auth')

//Contact mail routes

Route::post('/contactar-mail-simple', '[email protected]');

Route::post('/contactar-mail-avanzado', '[email protected]');

//Resource routes 

Route::resource('globals','GlobalsController');

Route::resource('posts','PostController');

Route::resource('sliders','SliderController');

Route::resource('reviews','ReviewController');

Route::post('/subscripcion', '[email protected]')->name('sub');


//Authentication Routes...

Route::get('login', 'Auth\[email protected]')->name('login');
Route::get('/logout', '\App\Http\Controllers\Auth\[email protected]');
Route::post('login', 'Auth\[email protected]');
Route::post('logout', 'Auth\[email protected]')->name('logout');

//Registration Routes...

//Route::get('register', 'Auth\[email protected]')->name('register');
//Route::post('register', 'Auth\[email protected]');

//Password Reset Routes...

Route::get('password/reset', 'Auth\[email protected]')->name('password.request');
Route::post('password/email', 'Auth\[email protected]')->name('password.email');
Route::get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset');
Route::post('password/reset', 'Auth\[email protected]');

Gabotronix started a new conversation AJAX POST Request Throws "MethodNotAllowedHttpException No Message" Error Right After I Submit It • 1 week ago

Hi, I'm trying to make the basic subscription service, sasly laravel is throwing the following error right after I submit the form via AJAX POST request:

No message```

What could be the cause of this?

Route:
```Route::post('/subscripcion', '[email protected]')->name('sub');```

JQuery code:
```php
$(document).ready(function(){
    
    
    
    $(".startSubscription").click(function(){
        var form = $(this).closest('form');
        $('.form_error_text').hide();
        $('.form_valid_text').hide();
        console.log('button start subscription clicked');
        
        var emailval=$("input[name='email']").val();
        
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({
            
            async: true,
            cache: false,
            url: '{{ route('sub') }}',
            type: 'POST',
            data: 
            {
                
            'email': emailval
            
            },
            dataType: 'JSON',
            
            success: function (data) { 
                $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                form.trigger("reset");
                console.log(data.success);
            },
            
            error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
                
                $.each(errors , function(){
                    $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                }); 
            }

        }); 
    });
    

});

Controller:

<?php

namespace App\Http\Controllers;

use App\Emails;
use Illuminate\Http\Request;
use App\Http\Requests\StoreSubbedMail;

class SubscriptionController extends Controller
{
    
    
    
    
    public function index()
    {
        //
    }

    
    
    
    public function create()
    {
        //
    }

    
    
    
    public function store(StoreSubbedMail $request)
    {
        $email = new Emails();
        $email->subbed_mail = $request->email;
        $email->save();
        
        return response()->json(['success'=>'Te subscribiste correctamente!'], $email);
    }

Form request:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreSubbedMail extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'subbed_mail' => 'required|email|unique:emails',
        ];
    }
}

5th July, 2018

Gabotronix started a new conversation Reading XML With JQuery And AJAX From Public Directory • 2 weeks ago

Hi everybody, given a XML file inside the public directory like this public -> xml -> restaurant.xml

I want to use an AJAX GET call via JQuery to read the xml nodes in there and append rows to my table with the gathered data.

Question is how would this look in my controller? how can I get into that xml file? So far I have my JQuery code almos done, AJAX url is empty.

JQuery:

var name;
    var half-price;
    var full-price;

    
    $.ajax({
        type: "GET",
        url: "what should I put here?",
        dataType: "xml",
        success: function(xml){
            $(xml).find('starter').each(function(){
                if($(this).attr('name').text() != 'no' && !=''){name = $(this).attr('name').text()};
                if($(this).attr('half-price').text() != 'no' && !=''){price = $(this).attr('half-price').text()};
                if($(this).attr('full-price').text() != 'no' && !=''){price = $(this).attr('full-price').text()};
                
                var menu_row = '<tr class="row">';
                    menu_row += '<td>' + name + '</td>';
                    menu_row += '<td>' + half-price + '</td>';
                    menu_row += '<td>' + full-price + '</td>';
                    menu_row += '</tr>';
    
                $('.entry_table_container[data-link=' + linked_entry + ']').append(menu_row);
                $('.container').append('');
            });
        },
        error: function() {
            alert("An error occurred while processing XML file.");
        }
    });

My XML file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<!--ENTRANTES-->
<starter name="primero" half-price="no" full-price="no" description="no" featured="no" image="no"></starter>
<starter name="segundo" half-price="no" full-price="no" description="no" featured="no" image="no"></starter>
<starter name="tercero" half-price="no" full-price="no" description="no" featured="no" image="no"></starter>
<starter name="cuarto" half-price="no" full-price="no" description="no" featured="no" image="no"></starter>
<starter name="quinto" half-price="no" full-price="no" description="no" featured="no" image="no"></starter>
<starter name="sexto" half-price="no" full-price="no" description="no" featured="no" image="no"></starter>

Any help would be appreciated.

3rd July, 2018

Gabotronix started a new conversation Failing To Get Input Values From My Form Into FormData Object • 2 weeks ago

Hi, I'm trying to store a new slider into my database via AJAX POST request to resource controller, however the data I fill into my form is not being sent since I'm getting the following error:

errors
:
body
:
["The body must be at least 10 characters."]
image
:
["The image must be a file of type: jpeg, jpg, png ."]
title
:
["The title must be at least 5 characters."]
__proto__
:
Object
message
:
"The given data was invalid."

This is obviously the request failing validation because input values are not properly being retrieved, I'm using formData for this :

This is my new slider modal, this is where I fill all the fields and send them via POST request after I click the button with class form_new_button:

<div class="modal_overlay_maincontainer closeable form_new_modal" data-link="sliders">
    <form class="modal_container" method="POST" >
        <i class="close fa fa-times-circle" title="Cerrar"></i>
        <h2 class="modal_title">Nueva Diapositiva</h2>
        <div class="modal_body_container">
            <div class="modal_body_check_container">
                <span class="modal_body_options_title">Visible</span>
                <input class="modal_body_check" name="isVisible" type="checkbox"  title="La diapositiva se subirá al pasador de diapositivas">
            </div>
            <div class="modal_body_check_container">
                <span class="modal_body_options_title">Imagen</span>
                <input type="file" name="image">
            </div>
            <input class="modal_input" type="text" name="title" placeholder="Titulo de la diapositiva" required>
            <textarea class="modal_input_textarea" name="body" placeholder="Contenido de la diapositiva" required></textarea>
        </div>
        <div class="modal_footer_container">
            <button class="modal_footer_add_button form_new_button" type="button" data-link="sliders" title="Crear nueva entrada">Crear</button>
            <button class="modal_footer_reset_button form_reset_button" type="button" title="Resetear los campos">Reset</button>
        </div>
    </form>
</div>

This is my form request for storing sliders:

public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            
            'title' => 'min:5|max:100',
            'body' => 'min:10|max:250',
            'image' => 'required | mimes:jpeg,jpg,png | max:1000',
            
        ];
    }

Here is my store method inside my resource controller, this is where the POST request is sent and where I sav a new slider in the database:

public function store(StoreSlider $request)
    {
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = $request->image;
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json($slider);
    }

1st July, 2018

Gabotronix started a new conversation Data Showing As "undefined" When Printing Values Into Blade • 2 weeks ago

Hi, I'm trying to populate a table aftersome JSON data I gather, but for some reason it's showing as undefined which is really weird since I console log the JSON data and this is what I get:

0
:
{id: 1, title: "Titulo del slider", description: "Descripcion del primer slider", image: "img/Res1.jpg", isVisible: 1, …}
1
:
{id: 2, title: "Titulo del slider", description: "Descripcion del primer slider", image: "img/Res1.jpg", isVisible: 1, …}
2
:
{id: 3, title: "Titulo del slider", description: "Descripcion del primer slider", image: "img/Res1.jpg", isVisible: 1, …}
length
:
3

And this is what I see in my view: https://i.imgur.com/lqxoizI.png

Since I'm getting a valid JSON response I think the problem has to be the way I iterate through this info, this is my JQuery code:

var linked_entry;
    
    var sliders_row = '<tr>';
    sliders_row += '<td>' + this.id + '</td>';
    sliders_row += '<td>' + this.title + '</td>';
    sliders_row += '<td>' + this.description + '</td>';
    sliders_row += '<td>' + this.image + '</td>';
    sliders_row += '<td>' + this.isVisible + '</td>';
    sliders_row += '<td class="entry_table_options_container">';
    sliders_row += '<i class="fa fas fa-pencil-alt" data-id="'+ this.id + '" data-title="'+ this.title +'" data-content="'+ this.description +'" data-image="'+ this.image +'" title="Editar" style="background-color:#5BC0DE;"></i>';
    sliders_row += '<i class="fa far fa-trash-alt" data-id="'+ this.id +'" data-title="'+ this.title +'" data-content="'+ this.description +'" data-image="'+ this.image +'" title="Borrar" style="background-color:#D9534F;"></i>';
    sliders_row += '</td>';
    sliders_row += '</tr>';
    
    var csrf = $('meta[name=csrf-token]').attr('content');
    console.log(csrf);
    
    $('.sidebar_entry_container').click(function(e){
        e.preventDefault();
        linked_entry = $(this).attr("data-link");
        $('.entry_container').removeClass('visible');
        $('.entry_container[data-link=' + linked_entry + ']').addClass('visible');
        console.log(linked_entry);
        
        
        
        $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        
        
        $.ajax({
            type: 'GET',
            url:  '/' + linked_entry + '',
            
            success: function(data) {
                console.log(data);
                $.each(data, function () {
                    $('.entry_table_container[data-link=' + linked_entry + ']').append(sliders_row);
                });
                
            },
            
            error: function(data) {
                
                alert('Something failed');              
            }
        });   
    });

Gabotronix started a new conversation Uncaught SyntaxError: Unexpected Identifier In Javascript Console • 2 weeks ago

I'm getting the following error in console: "Uncaught SyntaxError: Unexpected identifier"

var sliders_row = "";
    
    sliders_row +="<tr>";
    sliders_row +="<td>' + this.id + '</td>";
    sliders_row +="<td>' + this.title + '</td>";
    sliders_row +="<td>' + this.description + '</td>";
    sliders_row +="<td>' + this.image + '</td>";
    sliders_row +="<td>' + this.isVisible + '</td>";
    sliders_row +="<td class="entry_table_options_container">";
    sliders_row +="<i class="fa fa-info-circle" data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +"  title="Ver" style="background-color:#77DD77;"></i>";
    sliders_row +="<i class="fa fas fa-pencil-alt "  data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +" title="Editar" style="background-color:#5BC0DE;"></i>";
    sliders_row +="<i class="fa far fa-trash-alt "  data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +" title="Borrar" style="background-color:#D9534F;"></i>";
    sliders_row +="</td>";
    sliders_row +="</tr>";

I'm trying to append various html elements to a table header and ran into this issue, the error appears to be in this line:

sliders_row +="<td class="entry_table_options_container">";

And I can't seem to find anything wrong with this? Also, is there a less laborious way to append huge ammounts of html elements?

Gabotronix left a reply on How Can I Loop Throught My JSON And Append Various Divs To My Table With JQuery? • 2 weeks ago

I did some research and came up with this:

var sliders_row = "";
    
    sliders_row +="<tr>";
    sliders_row +="<td>' + this.id + '</td>";
    sliders_row +="<td>' + this.title + '</td>";
    sliders_row +="<td>' + this.description + '</td>";
    sliders_row +="<td>' + this.image + '</td>";
    sliders_row +="<td>' + this.isVisible + '</td>";
    sliders_row +="<td class="entry_table_options_container">";
    sliders_row +="<i class="fa fa-info-circle" data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +"  title="Ver" style="background-color:#77DD77;"></i>";
    sliders_row +="<i class="fa fas fa-pencil-alt "  data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +" title="Editar" style="background-color:#5BC0DE;"></i>";
    sliders_row +="<i class="fa far fa-trash-alt "  data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +" title="Borrar" style="background-color:#D9534F;"></i>";
    sliders_row +="</td>";
    sliders_row +="</tr>";

However I'm getting this error: Uncaught SyntaxError: Unexpected identifier

In this line: sliders_row +="<td class="entry_table_options_container">";

Gabotronix left a reply on How Can I Loop Throught My JSON And Append Various Divs To My Table With JQuery? • 2 weeks ago

Yes, I updated my KQuery code like this:

var linked_entry;
    
    var csrf = $('meta[name=csrf-token]').attr('content');
    console.log(csrf);
    
    $('.form_show_results').click(function(){
        linked_entry = $(this).attr("data-link");
        
        
        
        $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        
        
        $.ajax({
            type: 'GET',
            url:  '/' + linked_entry + '',
            
            success: function(data) {
                console.log(data);
                $('.form_table_results').removeClass('visible');
                $('.form_table_results[data-link=' + linked_entry + ']').addClass('visible');
                $.each(data, function () {
                    $('.entry_table_container[data-link=' + linked_entry + ']').append('');
                });
                
            },
            
            error: function(data) {
                
                alert('Something failed');              
            }
        });   
    });

And this is the html I'm trying to append:

<tr class="">
                <td>' + this.id + '</td>
                <td>' + this.title + '</td>
                <td>' + this.description + '</td>
                <td>' + this.image + '</td>
                <td>' + this.isVisible + '</td>
                <td class="entry_table_options_container">
                    <i class="fa fa-info-circle" data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +"  title="Ver" style="background-color:#77DD77;"></i>
                    <i class="fa fas fa-pencil-alt "  data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +" title="Editar" style="background-color:#5BC0DE;"></i>
                    <i class="fa far fa-trash-alt "  data-id="+ this.id +" data-title="+ this.title +" data-content="+ this.description +" data-image="+ this.image +" title="Borrar" style="background-color:#D9534F;"></i>
                </td>
            </tr>

But how can I get all that html appended, I'd like to get it all inside a $sliders_row_results variable, is something like that possible to do?

Gabotronix started a new conversation How Ca I Append Various Divs To My Table With JQuery? • 2 weeks ago

I'm retrieving all sliders from my database via JQuery GET Ajac call, I recieve this info in JSON format, now I want to append each of the results I gathered to my table header:

This is my JQuery call:

var linked_entry;
    
    var csrf = $('meta[name=csrf-token]').attr('content');
    console.log(csrf);
    
    $('.form_show_results').click(function(){
        linked_entry = $(this).attr("data-link");
        
        
        
        $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        
        
        $.ajax({
            type: 'GET',
            url:  '/' + linked_entry + '',
            
            success: function(data) {
                console.log(data);
                $('.form_table_results').removeClass('visible');
                $('.form_table_results[data-link=' + linked_entry + ']').addClass('visible');
                $('.form_table_results[data-link=' + linked_entry + ']').sppend('');
                
    });
            },
            
            error: function(data) {
                
                alert('Something failed');              
            }
        });   
    });

This is the portion I want to append to my table header, but how can I get all this html work into there?

<tr class="item{{$slider->id}}">
                <td>{{$post->id}}</td>
                <td>{{$post->title}}</td>
                <td>{{App\Slider::getExcerpt($slider->content)}}</td>
                <td>{{$post->image}}</td>
                <td>{{$post->isVisible}}</td>
                <td class="entry_table_options_container">
                    <i class="fa fa-info-circle" data-id="{{$post->id}}" data-title="{{$slider->title}}" data-content="{{$post->slider}}" data-image="{{$post->slider}}"  title="Ver" style="background-color:#77DD77;"></i>
                    <i class="fa fas fa-pencil-alt "  data-id="{{$post->id}}" data-title="{{$slider->title}}" data-content="{{$post->slider}}" data-image="{{$post->slider}}" title="Editar" style="background-color:#5BC0DE;"></i>
                    <i class="fa far fa-trash-alt "  data-id="{{$post->id}}" data-title="{{$slider->title}}" data-content="{{$post->slider}}" data-image="{{$post->slider}}" title="Borrar" style="background-color:#D9534F;"></i>
                </td>
            </tr>

This is the result I'm getting:

How can I loop through each of the results and append the html to my table header?

30th June, 2018

Gabotronix started a new conversation Getting Error 500 When Sending GET Ajax Request To Resource Controller/routes • 2 weeks ago

Hi, I'm trying to gather sliders for my custom admin panel, I do this with a GET request to my resource controller and routes, for some reason I'm getting a 500 error even thoug I'm sending csrf token and my routes seem fine.

Any idea what could be causing this:

Here is my JQuery AJAX call:

$('.form_show_results').click(function(){
        linked_entry = $(this).attr("data-link");
        
        
        
        $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        
        
        $.ajax({
            type: 'GET',
            url:  '/' + linked_entry + '',
            
            success: function(data) {
                alert('Posts gathered');
            },
            
            error: function(data) {
                alert('Something failed');   
            }
        });   
    });

Here are my routes:


Route::resource('sliders','SliderController');

Here is my Slider controller, afaik my GET request without id parameter should hit the index method of the resource controller, am I right?

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SliderController extends Controller
{
    
    
    
    
    public function index()
    {
        $sliders = Slider::all();
        
        return response()->json($sliders);
    }

Gabotronix started a new conversation Passing Data Array To Blade View And Looping Throught It • 2 weeks ago

Hi, I'm new to laravel, I want to push into a single array all the variables I gather in side my controller method, then I want to show the values of each key inside my blade template.

Here is my controller:

public function admin()
    {
        
        $restaurant_name = config('globals.web_name');
        $restaurant_description = config('globals.web_description');
        $restaurant_bio = config('globals.restaurant_bio');
        $full_address = config('globals.full_address');
        $city_zip = config('globals.city_zip_address');
        $booking_phone = config('globals.booking_phone');
        $client_mail = config('globals.client_mail');
        
        
        
        
        $pageInfo = 
        [
            'page_title'      => 'Panel de administración',
            'menu_active'     => '',
            'submenu_active' => '',
        ];

        
        return view('admin.index', compact('pageInfo','restaurant_name','restaurant_description', 'restaurant_bio','full_address', 'city_zip', 'booking_phone', 'client_mail'));
    }

You see al these variables, how can I get them inside a single array of key -> value called $config_data and access these keys from the view?

Now in my blade view:

<div class="entry_container form_table_results " data-link="post" style="">
        <div class="entry_header_container">
            <span class="entry_header_title">Información general</span>
            {{--<a class="entry_header_new_button form_show_new_modal"  href="" title="Crear nuevo" data-link="post"><i class="fa fa-plus"></i>Nuevo</a>--}}
        </div>
        <table class="entry_table_container">
            <tr>
                <th class="entry_table_header" width="20%">Name</th> 
                <th class="entry_table_header" width="50%">Value</th> 
                {{ csrf_field() }}
            </tr>
            @foreach($config_data as $data)
            <tr">
                <td>{{$data->name}}</td>
                <td>{{$data->value}}</td>
                <td class="entry_table_options_container">
                    <i class="fa fas fa-pencil-alt " title="Editar" data-name="{{$data->name}}" data-value="{{$data->value}}" style="background-color:#5BC0DE;"></i>
                </td>
            </tr>
            @endforeach
        </table>
    </div>
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.