Gabotronix

Experience

9,060

0 Best Reply Awards

  • Member Since 5 Months Ago
  • 45 Lessons Completed
  • 1 Favorite

14th September, 2018

Gabotronix left a reply on Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts. • 6 days ago

I see, so what pattern would you recommend me @martinbean.

Just using laravel for server rendering the views and adding the neccesary components to blade templates, since I have a single vue instance would it be possible to import components and classes only when needed?

What other structure patterns exist for easily maintaining laravel + vue.js MPAs

Gabotronix started a new conversation Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts. • 6 days ago

I thought about the following MPA - SPA hybrid, where I basically treat each page as an SPA, but still reloading pages to transit from one page to another (index.blade.php to posts.blade.php) like the habitual MPA. This methods uses laravel routing, session and auth poweful features to render a blade template wich contains a single vue.js component .

Imagine you are at the main page, you will have something like this:

@extends('layouts.master')
@section('content')
<body id="vue_root">
    <page-index data={{ json encoded data from backend }}></page-index>
</body>
@endsection

As you can see I pass a json object as a prop to vue component, this prop contains all needed data for vue to render.

When using this approach of treating each page as a component I can use vue.js single files to contain all the markup, logic (vue component methods and style) into a single file wich will make it easier for me to test and debug.

I have a single vue.js root instance where I register all page components.

However since I'm using laravel controllers as a backend for retrieving all the data along with blade views I will also have to create vue.js components and laravel blade templates, that sounds like double work to me.

What do yout think of this pattern? is it good? any ideas to improve this, should I use inline-templates instead (that way I would not need to make corresponding blade templates and vue.js page components.

Gabotronix started a new conversation Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts. • 6 days ago

I thought about the following MPA - SPA hybrid, where I basically treat each page as an SPA, but still reloading pages to transit from one page to another (index.blade.php to posts.blade.php) like the habitual MPA. This methods uses laravel routing, session and auth poweful features to render a blade template wich contains a single vue.js component .

Imagine you are at the main page, you will have something like this:

@extends('layouts.master')
@section('content')
<body id="vue_root">
    <page-index data={{ json encoded data from backend }}></page-index>
</body>
@endsection

As you can see I pass a json object as a prop to vue component, this prop contains all needed data for vue to render.

When using this approach of treating each page as a component I can use vue.js single files to contain all the markup, logic (vue component methods and style) into a single file wich will make it easier for me to test and debug.

I have a single vue.js root instance where I register all page components.

However since I'm using laravel controllers as a backend for retrieving all the data along with blade views I will also have to create vue.js components and laravel blade templates, that sounds like double work to me.

What do yout think of this pattern? is it good? any ideas to improve this, should I use inline-templates instead (that way I would not need to make corresponding blade templates and vue.js page components.

Gabotronix started a new conversation SEO Questions About Using Blade To Show Whole Page Vue.js Components In MPA • 6 days ago

Hi, So I'm thinking about the structure for my restaurant web page which will use laravel as the back-end (routing and displaying blade views to the browser, easy auth system and sessions) and vue.js for the front-end (I have a single vue instance where I register components, this components are each one a view, a whole page, most of these pages have 2 or 3 components nested, like an image slider, to-top anchor, I use axios to fetch my API endpoints without refreshing the page plus many CRUD operations from an admin panel).

This is how my index.blade.php view looks ( www.domain.com/ ), I have many views like posts.index.blade.php...

@extends('layouts.master')
@section('content')
    <page-index></page-index)
@endsection

As you can see, I want to treat each page as a vue.component with many components nested inside of each page component).

I have a few questions about possible complications using this structure.

  1. When displaying views I always return a json object with all the data I want to render on blade, since each page is basically a vue.js component loaded via javascript how will I able to loop through the dishes, events and posts I fetched from the backend.

  2. Since the whole page content is rendered via javascript won't this affect negatively SEO?? afaik search engones crawlers won't fetch the content displayed by javascript.

Is this a good practice, is this the best way to handle laravel + vue.js non-SPA?

17th August, 2018

Gabotronix started a new conversation Retrieving Resluts By Category Name Instead Of Id • 1 month ago

So I have this relationship between products and productcategories, one product belongs to a category and a category can hold many products, problem is I want to retrieve all products belonging to a productcategory by name instead of using id.

Something similary looking to this??

public function index()
    {
        Product::where(productcategory->name, 'Starters')->get();
    }

These are my migrations:

//CREATE PRODUCTS TABLE
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('image')->nullable();
            $table->boolean('available')->default(true);
            $table->string('half');
            $table->string('full');
            $table->timestamps();
        });
        
        
        
        
        //CREATE PRODUCT CATEGORIES TABLE
        Schema::create('productcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('image')->nullable();
            $table->timestamps();
        });
        DB::table('productcategories')->insert([
            'name' => 'Starters'),
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Salads'),
        ]);
        DB::table('productcategories')->insert([
            'name' => 'Soups'),
        ]);

And my models:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductCategory extends Model
{
    protected $table = 'productcategories';
    
    
    
    
    public function products()
    {
        return $this->HasMany('App\Product');
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    
    
    
    
    public function orders()
    {
        return $this->belongsToMany('App\Order');
    }
    
    
    
    
    public function productcategory()
    {
        return $this->belongsTo('App\ProductCategory');
    }
}

3rd August, 2018

Gabotronix started a new conversation Error: "count(): Parameter Must Be An Array Or An Object That Implements Countable" • 1 month ago

I'm trying to count the posts wich are set to visible but I'm getting the following error:

 ErrorException (E_WARNING)
count(): Parameter must be an array or an object that implements Countable

Here is my code:

$active_posts_count = count(Post::where('isVisible', 1));

The error is pretty self explanatory but I don't know how to count visible posts otherwise

29th July, 2018

Gabotronix started a new conversation "Too Few Arguments To Function Illuminate\Support\MessageBag::has()" Error In My Login Blade Template • 1 month ago

So I'm getting the following message on my login blade template:

Too few arguments to function Illuminate\Support\MessageBag::has(), 0 passed in C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Support\ViewErrorBag.php on line 95 and exactly 1 expected (View: C:\xampp\htdocs\Restaurante1\resources\views\auth\login.blade.php)

I'm 100% sure it's because this part:

@if($errors->has())
            @foreach ($errors->all() as $error)
            <div class="auth_login_modal_errors_error_container" style="">
                <i class="fa fa-asterisk" style=""></i>
                <span class="auth_login_modal_errors_error_text" style="">{{ $error }}</span>
            </div>
            @endforeach
        @endif 

This my complete login blade template:

<form class="auth_login_modal_maincontainer" method="POST" action="{{ route('login') }}" style="">
    <span class="auth_login_modal_title" style="">INICIAR SESIÓN</span>
    <div class="horizontal_gradient_line" style="margin:15px 0px;"></div>
    <div class="auth_login_modal_inputs_container" style="">
        <div class="auth_login_modal_input_container" style="">
            <div class="auth_login_modal_input_icon" style="">
                <i class=" fa fa-at" style=""></i>
            </div>
            <input class="auth_login_modal_input" style="" id="email" name="email" value="{{ old('email') }}" type="text" placeholder="CORREO ELECTRÓNICO" required autofocus>
        </div>
        <div class="auth_login_modal_input_container" style="">
            <div class="auth_login_modal_input_icon" style="">
                <i class=" fa fa-lock" style=""></i>
            </div>
            <input class="auth_login_modal_input" style="" id="password" name="password" type="password" placeholder="CONTRASEÑA" required>
        </div>
        <div class="auth_login_modal_label_container" style="">
            <input class="auth_login_modal_label_checkbox" style="" name="remember" type="checkbox" {{ old('remember') ? 'checked' : '' }}>
            <span class="auth_login_modal_label_text" style="">Recuerdame</span>
        </div>
    </div>
    <div class="auth_login_modal_errors_container" style="">
    
        @if($errors->has())
            @foreach ($errors->all() as $error)
            <div class="auth_login_modal_errors_error_container" style="">
                <i class="fa fa-asterisk" style=""></i>
                <span class="auth_login_modal_errors_error_text" style="">{{ $error }}</span>
            </div>
            @endforeach
        @endif 
    
    </div>
    <div class="horizontal_gradient_line" style="margin:15px 0px;"></div>
    <div class="auth_login_modal_buttons_container" style="">
        <button class="auth_login_modal_button" type="submit" title="Iniciar sesión " style="background-color:rgb(130, 201, 30);">Iniciar sesión</button>
        <button class="auth_login_modal_button" type="button" title="Resetear campos" id="resetValues" style="background-color:rgb(51, 122, 183);">Resetear campos</button>
    </div>
</form>

25th July, 2018

Gabotronix started a new conversation Show Modal Only Once With Cookies • 1 month ago

Hi, I want to show a modal only once, this could probably be achieved with cookies but I don't know how to do this:

what I want to do is in my blade template check if cookie "modal" is set, if it's set I don't show the modal and if it's not set I show the modal and set cookie to true?

This is what I came up with so far:

@if ($modal->isActive && Cookie::get('cookie_modal') !== null )
    <!--cookie is set, don't show modal-->
@elseif ($modal->isActive && Cookie::get('cookie_modal') == null )
    <!--show_modal and set cookie to true so that next time modal doesn't show up-->
    {{Cookie::make('cookie_modal', true, 60) }}
    <div id="modal" style="width:100%; height:500px; position:relative; background-color:red; margin:25px auto;"></div>
@endif 

24th July, 2018

Gabotronix started a new conversation Explanation Of Why Save Method Is Not Working • 1 month ago

Hi, so when I perform a query where I check for the name field of a database entry and save the new value I get an error, however when I fing that same entry by id and save it to database it works perfectly, I was looking for an explanation on this.

My code:

public function update_booking_phone(Request $request)
    {
        $global = Globals::findOrFail($request->id);
        $global->value = $request->value;
        $global->save();
        
        $show_booking_phone = Globals::findOrFail(5);//Globals::where('name', 'Teléfono para mostrar')->first()->get();
        $prefixed_phone = '+34'.$request->value;
        $show_booking_phone->value = $prefixed_phone;
        $show_booking_phone->save();
        
        
        return response()->json([
        
            'global' => $global,
            'prefixed_phone' => $prefixed_phone,
            'success' => 'Teléfono actualizado correctamente',
        ]);
    }

The commented section of the code gives me following error when executed:

Method Illuminate\Database\Eloquent\Collection::save does not exist

23rd July, 2018

Gabotronix left a reply on Retrieving Category Name Belonging To Post • 1 month ago

Changed

$posts = Post::with('category')->all();

for

$posts = Post::with('category')->get();

and it's working like a charm now!!

Gabotronix left a reply on Retrieving Category Name Belonging To Post • 1 month ago

Yeah I already changed it:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['title', 'body', 'isVisible', 'image'];
    
    
    
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
    
    

    public static function getExcerpt($str, $startPos = 0, $maxLength = 30) {
        if(strlen($str) > $maxLength) {
            $excerpt   = substr($str, $startPos, $maxLength - 6);
            $lastSpace = strrpos($excerpt, ' ');
            $excerpt   = substr($excerpt, 0, $lastSpace);
            $excerpt  .= ' [...]';
        } else {
            $excerpt = $str;
        }

        return $excerpt;
    }
}
namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';
    protected $fillable = ['name', 'isVisible'];
    
    
    
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

Gabotronix left a reply on Retrieving Category Name Belonging To Post • 1 month ago

I get following error:

message: "Method Illuminate\Database\Query\Builder::all does not exist.", exception: "BadMethodCallException", file: "C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php", line: 2816, trace: (57) […] }

Gabotronix started a new conversation Retrieving Category Name Belonging To Post • 1 month ago

Hi, I'm displaying all posts in database, each post belongs to ONE category, problem is when I print all posts data I can only access category_id field (since this is fk), however I want to display category name instead (name is another field of Category model).

I don't know how I could go to do this:

This is where I retrieve posts data (via GET AJAX call) and append posts data to table body:

case "posts":
                    
                $.ajax({

                    async: true,
                    url: '/posts',
                    type: 'GET',
                    dataType: 'JSON',
             
                    success: function (data) { 
                    
                        console.log(data.posts);
                            
                        $('.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.category_id + '</td>';
                            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);
                    }
                
                });

This is where I retrieve all posts data (resource controller):

public function index()
    {
        $posts = Post::all();
        
        return response()->json([
        
            'success' => 'Todas las publicaciones recogidas',
            'posts' => $posts,
        ]);
    }

This is migration where I create posts and migrations:

//CREATE CATEGORIES TABLE
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL CATEGORIES TABLE WITH CATEGORIES
        DB::table('categories')->insert([
            'name' => 'Evento',
        ]);
        DB::table('categories')->insert([
            'name' => 'Oferta',
        ]);
        DB::table('categories')->insert([
            'name' => 'Notícia',
        ]);
        DB::table('categories')->insert([
            'name' => 'Artículo',
        ]);

Gabotronix started a new conversation Assingning Category To Post With Schema Builder • 1 month ago

Hi, In my migration where I create posts and categories table I want to assign a category to a post (EX: first post belongs to category with id 2), a post belongs to a single category and one category can have many posts.

This are my models:

Post Model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['title', 'body', 'isVisible', 'image'];
    
    
    
    public function category()
    {
        return $this->hasOne('App\Category');
    }
    
}

Category Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';
    protected $fillable = ['name', 'isVisible'];
    
    
    
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

This is the migration where I posts table and categories table:

//CREATE POSTS TABLE
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('body');
            $table->string('image')->nullable();
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL POSTS TABLE WITH DUMMY POSTS
        DB::table('posts')->insert([
            'title' => config('globals.post_title_1'),
            'body' => config('globals.post_body_1'),
            'image' => config('globals.post_image_1'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'title' => config('globals.post_title_2'),
            'body' => config('globals.post_body_2'),
            'image' => config('globals.post_image_2'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        DB::table('posts')->insert([
            'title' => config('globals.post_title_3'),
            'body' => config('globals.post_body_3'),
            'image' => config('globals.post_image_3'),
            'isVisible' => true,
            'created_at' => Carbon::now(),
        ]);
        
        
        
        
        //CREATE CATEGORIES TABLE
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL CATEGORIES TABLE WITH CATEGORIES
        DB::table('categories')->insert([
            'name' => 'Evento',
        ]);
        DB::table('categories')->insert([
            'name' => 'Oferta',
        ]);
        DB::table('categories')->insert([
            'name' => 'Noticia',
        ]);
        DB::table('categories')->insert([
            'name' => 'Articulo',
        ]);

22nd July, 2018

Gabotronix started a new conversation Trying To Get Property 'id' Of Non-object • 1 month ago

Hi, I created a route where I show a single post by it's id, however when I try to show the post in blade template I get the following error:

Trying to get property 'id' of non-object (View: C:\xampp\htdocs\Restaurante1\resources\views\eventos\show.blade.php)

This is my controller where I retrieve post by id:

public function evento($id)
    {
        
        $post = Post::findOrFail($id);
        
        $post_title = $post->title;
        
        //dd($post_title);
        
        $pageInfo = 
        [
            'page_title'      => 'Publicaciones: '.$post_title,
            'menu_active'     => '',
            'submenu_active' => '',
        ];
        
        //dd($pageInfo['page_title']);

        
        return view('eventos.show', compact('pageInfo', 'post'));
    }

This is the dumped data of the post, to confirm I retrieved it correctly: https://i.imgur.com/x5DrwbH.png

Now, this is my blade template where I try to show the complete post to user (this is where the error is detected):

<div class="section_post_alma_contents_container">
        @foreach($post as $post)
        <div id="{{ $post->id }}" class="section_post_alma_content_container" style="">
            <div class="section_post_alma_content_header_container" style="">
                <div class="section_post_alma_content_header_main_container" style="">
                    <div class="section_post_alma_content_header_main_icon" style="">
                        <i class="fa fa-newspaper" style=""></i>
                    </div>
                    <span class="section_post_alma_content_header_main_title" style="">{{ $post->title }}</span>
                </div>
                <div class="section_post_alma_content_header_info_container" style="">
                    <div class="section_post_alma_content_header_info_date_container" style="">
                        <i class="fa fa-calendar" style=""></i>
                        <span class="section_post_alma_content_header_info_date_text" style="">Publicado el</span>
                        <span class="section_post_alma_content_header_info_date_at" style="">{{ $post->created_at }}</span>
                    </div>
                    <div class="section_post_alma_content_header_info_date_container" style="">
                        <span class="section_post_alma_content_header_info_date_text" style=""></span>
                        <i class="fa fa-user" style=""></i>
                        <span class="section_post_alma_content_header_info_date_at" style="">{{ $config['web_name']['value'] }}</span>
                    </div>
                </div>
            </div>
            <div class="section_post_alma_content_image" style="background-image:url('{{ url( $post->image ) }}');"></div>
            <p class="section_post_alma_content_paragraph" style="">{{ $post->body }}</p>
            <div class="section_post_alma_content_links_container" style="">
                <a class="section_post_alma_content_link_container" href="tel:{{ $config['booking_phone']['value'] }}" style="">
                    <i class="fa fa-phone" style=""></i>
                    <span class="section_post_alma_content_link_text" style="">{{ $config['booking_phone']['value'] }}</span>
                </a>
                <a class="section_post_alma_content_link_container" href="/contacta-con-nosotros" style="">
                    <i class="fa fa-envelope" style=""></i>
                    <span class="section_post_alma_content_link_text" style="">ESCRIBENOS</span>
                </a>
            </div>
            <span class="horizontal_gradient_line"></span>
        </div>
        @endforeach
    </div>

21st July, 2018

Gabotronix left a reply on Sorting Posts By Month • 1 month ago

That's exactly what I was looking for, thanks!

Gabotronix left a reply on Sorting Posts By Month • 1 month ago

No one? I just want to know how to "extract" month from the "created_at" carbon instance

Gabotronix left a reply on String Value Showing With [" "] Characters • 1 month ago

Very nice, thanks

Gabotronix left a reply on String Value Showing With [" "] Characters • 1 month ago

I understand, thanks!

Gabotronix started a new conversation String Value Showing With [" "] Characters • 1 month ago

So I just noticed this bug, when building the subject for my mailable the string is showing like this :

Nuevo reporte de bug en ["Nombre del Restaurante"]

Any idea why is it showing the [""] characters around the concatenated variable??

This is the method controller where I build the string:

public function contactar_reportar_bug(BugReport $request)
    {
        
        $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,

        ]);
    }

Gabotronix started a new conversation Sorting Posts By Month • 1 month ago

So I want to sort all posts by month, some kind of posts history by months , for this I want to use the "created_at" field of my Post model, how could I achieve this?

This is my posts migration:

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

This is my method controller where I want to gather all posts inside each month variable, don't know what database query should I perform to do this tho...

public function posts_by_month()
    {
        $january = Post::;
        $february = Post::;
        $march = Post::;
        
        return response()->json([
        
            'success' => 'All posts gathered by month',
            'january' => $january,
            'february' => $february,
            'march' => $march,
            /* ... */
        ]);
    }

This is jquery code where I append the results to each respective posts month container:

$.ajax({

        async: true,
        url: '/posts-by-month',
        type: 'GET',
        dataType: 'JSON',
             
        success: function (data) { 
                            
            $(".history[data-link='january']").append(generateHtml(data.january)); 
            $(".history[data-link='february']").append(generateHtml(data.february)); 
            $(".history[data-link='march']").append(generateHtml(data.march)); 
            $(".history[data-link='april']").append(generateHtml(data.april)); 
            /* ... */
        },
            
        error: function (data){
            var errors = data.responseJSON;
            console.log(errors);
        }
                
    });
    
    
    
    
    function generateHtml(data) {
        
        var post_template = '';

        $.each(data, function (index, item) {
            
            post_template += '<div style="width:auto; height:auto; display:flex; align-items:center; margin:5px 0px; margin-left:30px;">';
            post_template += '<i class="fa fa-circle" style="color:rgba(0,0,0,0.8); font-size:4px; margin-right:5px;"></i>';
            post_template += '<a href="" style="font-size:15px; color:rgba(0,0,0,0.7);">' + item.title + '</a>';
            post_template += '</div>';
            
        });

        return post_template;
    }

My blade template so you can better understand what I'm trying to do:

<div class="section_post_alma_history_container" style="">
        <span class="section_post_alma_history_title" style="">{{ $config['web_name']['value'] }}</span>
        <div class="section_post_alma_history_header_container" style="">
            <span class="section_post_alma_history_header_text" style="">Eventos</span>
            <span class="section_post_alma_history_header_year" style="">{{ now()->year }}</span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="january" style="">
            <span class="section_post_alma_history_month_text" style="">Enero<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="february" style="">
            <span class="section_post_alma_history_month_text" style="">Febrero<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="march" style="">
            <span class="section_post_alma_history_month_text" style="">Marzo<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="april" style="">
            <span class="section_post_alma_history_month_text" style="">Abril<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="may" style="">
            <span class="section_post_alma_history_month_text" style="">Mayo<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="march" style="">
            <span class="section_post_alma_history_month_text" style="">Junio<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="march" style="">
            <span class="section_post_alma_history_month_text" style="">Julio<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="august" style="">
            <span class="section_post_alma_history_month_text" style="">Agosto<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="september" style="">
            <span class="section_post_alma_history_month_text" style="">Septiembre<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="october" style="">
            <span class="section_post_alma_history_month_text" style="">Octubre<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="november" style="">
            <span class="section_post_alma_history_month_text" style="">Noviembre<i class="far fa-arrow-alt-circle-down" style=""></i></span>
        </div>
        <div class="section_post_alma_history_month_container history" data-link="december" style="">
            <span class="section_post_alma_history_month_text" style="">Diciembre<i class="far fa-arrow-alt-circle-down" style=""></i></span>
            
        </div>
    </div>

20th July, 2018

Gabotronix started a new conversation Appending Data To Divs Issue • 2 months ago

So I retrieve data via AJAX GET request and append it to a few containers however I have to define menu_row variable inside each $.each function (can't pass more arguments to $.each function sadly). This makes my code much more cluttered, my question is how could I solve this without the use of plugins??

I also tried using jquery clone but printing data doesn't work...

$.ajax({

            async: true,
            url: '/menu-todos',
            type: 'GET',
            dataType: 'JSON',
             
            success: function (data) { 
                
                console.log(data);
                console.log(data.success);
                
                
                
                $.each(data.starters, function (index, item) {
            
            
                    var menu_row_1 ='<div style="width:100%; height:30px; display:flex; padding:0px 25px; margin:0px 0px;">';
                      menu_row_1 += '<span style="width:70%; height:100%; display:flex; align-items:center; font-size:13px; color:rgba(0,0,0,0.8);">' + item.name + '</span>';
                      menu_row_1 += '<span style="width:15%; height:100%; display:flex; align-items:center; justify-content:flex-end; font-size:13px; color:rgba(0,0,0,0.8);">' + item.half + '</span>';
                      menu_row_1 += '<span style="width:15%; height:100%; display:flex; align-items:center; justify-content:flex-end; font-size:13px; color:rgba(0,0,0,0.8);">' + item.full + '</span>';
                      menu_row_1 += '</div>';

                                       //var menu_row = $('.section_menu_mada_page_row_container').clone();
                    
                      
                    $(".menu_container[data-link='starters']").append(menu_row_1);
                
                
                });
                
                $.each(data.salads, function (index, item) {
                    
                    
                    $(".menu_container[data-link='salads']").append(menu_row_1);
                                          //same thing here...
                });
                
                $.each(data.soups, function (index, item) {
                    $(".menu_container[data-link='soups']").append(menu_row_1);
                });
                
                $.each(data.fishes, function (index, item) {
                    $(".menu_container[data-link='fishes']").append(menu_row_1);
                });
                
                $.each(data.meats, function (index, item) {
                    $(".menu_container[data-link='meats']").append(menu_row_1);
                });
                
                $.each(data.desserts, function (index, item) {
                    $(".menu_container[data-link='desserts']").append(menu_row_1);
                });
                
                $.each(data.beers, function (index, item) {
                    $(".menu_container[data-link='beers']").append(menu_row_1);
                });
                
                $.each(data.wines, function (index, item) {
                    $(".menu_container[data-link='wines']").append(menu_row_1);
                });
            },
            
            error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
            }   
        });

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

Welp, I'm still getting the same mime validation error, I changed my form request:

 public function rules()
    {
        $rules = [
            'body' => 'required|string|min:5',
        ];

        if (request()->has('file')) {
            $rules['file'] = 'nullable|mimes:doc,pdf,docx,zip,odt,jpeg,bmp,png,jpg,svg|max:2000';
        }

    return $rules;
    }

And added the file check to my method controller:

public function contactar_reportar_bug(BugReport $request)
    {
        
        $bug = new Bug();
        $bug->body = $request->body;
        $bug->save();
        
        $uploadFile = null; 
        
        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,

        ]);
    }

And as recommended by Cronix I edited my mailable class to check if a file exists:

public function build()
    {
        
        if( is_null($this->uploadFile))
        {
            
            return $this->markdown('emails.bug_reports')
            ->from($this->sender_mail, 'BugReportGab')
            ->subject($this->subject);
            
        }
        
        
        return $this->markdown('emails.bug_reports')
        ->from($this->sender_mail, 'BugReportGab')
        ->subject($this->subject)
        ->attach($this->uploadFile, [
            'as' => $this->filename,
            'mime' => $this->mimetype,
        ]);
    }

19th July, 2018

Gabotronix left a reply on Getting Mimes Validation Fail When Not Uploading Optional File With AJAX • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months ago

That worked perfectly, thanks Cronix

Gabotronix left a reply on Can't Access Uploaded Images In The Browser • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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 • 2 months 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] • 2 months 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] • 2 months 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" • 2 months 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
Edit Your Profile
Update

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