nhayder

nhayder

Member Since 1 Year Ago

Doha

Experience Points 41,070
Experience Level 9

3,930 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 292
Lessons
Completed
Best Reply Awards 2
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

20 Aug
22 hours ago

nhayder started a new conversation How To Chain Eager Load Articles According To Categories And Subcategories

i have multiple widgets on the page i'm giving the user the ability to load articles according to his choice, by selecting category subcategory then hitting the submit button.

i'm having some difficulties on how to make a this relationship work.

// these are the widgets

widget 1
    - id
    - Politics
    - contentcategory // this is the main category
    - contentsubcategory // this is the sub-cateogry

widget 2
    - id
    - sport
    - contentcategory 
    - contentsubcategory

widget 3
    - id
    - lifestyle
    - contentcategory 
    - contentsubcategory

The main and sub category are save into the widget table using simple form, now i need to perform the relationship to fetch the articles.

article 1
    - id
    - title
    - category_id // this is the article main category
    - subcategory_id // this is the article sub-cateogry

article 2
    - id
    - title
    - category_id 
    - subcategory_id

article 3
    - id
    - title
    - category_id 
    - subcategory_id

i'm trying to get this type of relationship

$widget->category->subcategory->articles;

widget has one category -> category has many subs -> sub has many articles 

To achieve my purpose i need to make a relationship between these table so the widget main cat+subcat matches the article main cat +subcat.

How to perform this type of relationship, any idea ?????

13 Aug
1 week ago

nhayder left a reply on How To Use Laravel Localization In Vue

@morpheus7 thank you i didn't know about that package till you brought it up, i will definitely check it soon :-)

nhayder left a reply on How To Use Laravel Localization In Vue

Thank you for the time you took for explanation ? it looks like it will definitely work but i'm not sure if this is the recommended way to do that.

12 Aug
1 week ago

nhayder started a new conversation How To Use Laravel Localization In Vue

i'm using vuex, vue and laravel 5.8 on my multilingual app, i'm at a point to add localization to my vue component.

i didn't started yet but i'm checking what is the best way to extend laravel localization to some vue component on the app.

any recommendations on this matter ???

01 Aug
2 weeks ago

nhayder started a new conversation Testing With Chrome DevTools Returning Medium Vulnerability For [email protected]

i'm getting a [email protected] medium Vulnerability when i tested my laravel app with chrome devTools performance

https://snyk.io/vuln/npm:bootstrap?lh=4.1.0&utm_source=lighthouse&utm_medium=ref&utm_campaign=audit

snap shot available here https://www.dropbox.com/s/2ww6cu8fsq46bzf/Screen%20Shot%202019-08-01%20at%207.28.57%20PM.png?dl=0

anyone else having same issue ??? any fix for it ????

29 Jul
3 weeks ago

nhayder started a new conversation Axios Ajax Call Not Working On Safari

I'm fetching data on my app using axios like this


        async saveText({commit}, [id, text, name, wIndex]){

            commit('WORK_ON');

            await axios.put('/api/text', {

                elem: text,

                elemName : name,

                elemId: id,

            })

            .then(function (response) {


                Event.$emit('success'); 

            })

            .catch(function (error) {

                Event.$emit('requestAlertDanger'); 

            });

        },

the code is working fine on chrome but today i was testing the app on safari and was surprised that code is not working.

Any ideas why that is??? How do fix this issue

27 Jul
3 weeks ago

nhayder left a reply on Count Logged In Users

this solved it

function countOnlineUsers() {

    // get all users from cache
    $cachedUsers = json_decode(Cache::get('isOnline', []), true);
    
    $count = count($cachedUsers);

    return $count;
}

nhayder started a new conversation Count Logged In Users

I have a middleware that will add user to array every time a user login to his account

    public function handle($request, Closure $next)
    {
        if(Auth::check()) {
            
            $lastSeen = Carbon::now()->format('y-m-d H:i:s');

            $onlineUsers = json_decode(Cache::get('isOnline', '{}'), true);

            $onlineUsers[ Auth::id() ] = $lastSeen;

            Cache::put('isOnline', json_encode($onlineUsers), 60); // store for 2 minutes

        }

        return $next($request);
    }

Now i need to check how many users are in that array from blade template file ????

Any ideas on how to do this ????

22 Jul
4 weeks ago

nhayder left a reply on Spatie/laravel-sitemap Creating Empty Sitemap.xml

@cronix Yah, :-) worked after i uploaded the site to the internet, Thanx

21 Jul
4 weeks ago

nhayder left a reply on Spatie/laravel-sitemap Creating Empty Sitemap.xml

@bobbybouwmann actually the app.url was not matching so i changed is like this

Route::get('/sitemap', function(){

    SitemapGenerator::create('http://127.0.0.1:8000')->writeToFile('sitemap.xml');

    return 'Sitemap generated';

});

After the that change the file now need almost 2 minutes for be created and its still empty?

// this is the content of the file after its being created
<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
</urlset>

@snapey to answer you questions, 1- no i'm not using a command the file creation is directly on the web.php file 2- i'm running the app on localhost, but the files is being created every time 3- i'm using laravel 5.8 4- yes all my routes are in web.php

nhayder started a new conversation Spatie/laravel-sitemap Creating Empty Sitemap.xml

i'm using spatie/laravel-sitemap to generate sitemap.xml file dynamically, The package is not creating the site map but its always empty.

packager usrl : https://github.com/spatie/laravel-sitemap

created sitemap.xml

// this is what im getting every time
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
</urlset>

this is how im generating the file???

SitemapGenerator::create(config('app.url'))->writeToFile(public_path('sitemap.txt'));

if there is anyone who is using this package? can you see what is the problem

All the best

20 Jul
1 month ago

nhayder started a new conversation Can't Paginate Search Result Records?

this is the form

<form action="{{route('rp')}}" method="GET" role="search" enctype="multipart/form-data">
    @csrf
    <input type="text" name="search" class="search-input form-control" placeholder="@lang('translation.search')" required="true"/>

</form>

and i have this route to execute the search

Route::get('/rp', '[email protected]')->name('rp');

in my controller


    public function resultPage(Request $request)
    {


        $request->validate([

            'search' => 'required|string|min:3',

        ]);
        

        $query = User::query();

        $columns = ['firstname','familyname', 'email', 'language', 'adminnote','gender','address1','address2','company','city','postalcode','phone'];

        foreach($columns as $column){

            $query->orWhere($column, 'LIKE', '%' . $request->search . '%');
        }

        $results = $query->paginate(25);

        return view('admin.search', compact('results'));
        
    }

at the same time i'm using links() function to paginate results


@foreach($results as $user)
    
    // do something

@endif

{{ $results->links() }}

this is what i'm getting on the browser when submitting search from


http://127.0.0.1:8000/en/admin/rp?_token=YDZrO7i6h0ao7OSokwmttqL8YoONFNqf6z9pn9Cq&search=johan

when hover over the pagination button i'm getting these


http://127.0.0.1:8000/en/admin/rp?page=2 // and page=3 + 5 + 10  etc

the problem is that pationation is not working it basically stays on same page even after i click the next button

what seems to be the problem

?????

15 Jul
1 month ago

nhayder started a new conversation Uncaching Iframe Data Not Working

in my app a user can preview his personal page as it looks on phone and tablet and desktop computer , i'm loading a view inside and iframe to simulate multiple screen sizes.

<iframe src="/"></iframe> // this loads personal page of user as phone size

the iframe is doing its job perfectly and working fine, until a user change some settings on his personal page, then when he tries to preview it? iframe is still shows previous information inside the iframe.

the personal page has some caching already so using axios i'm clearing the cached files directly from controller.

Artisan::call('cache:clear');

The cache files are removed and axios is working as expected but, unfortunately, iframe is still showing old data every time, The only way i can see the new changes is when i refresh the page.

it looks like cache:clear is not uncaching the iframe data as expected, until i refresh the page.

so how to force my iframe to clear cached data without refreshing the page

any ideas???

14 Jul
1 month ago

nhayder started a new conversation Select Proper Value From Array Dynamically

in my app i have page footer are where it supposed to show copyright message dynamically according the users reading language.

the copyright data with multiple languages values is already stored in array that looks like this

// copyrights array
{
id: 1,
  de: "Alle Rechte vorbehalten - 2019.",
  en: "All rights reserved - 2019",
  es: "Todos los derechos reservados - 2019.",
  fr: "Tous droits réservés - 2019.",
}

from my page footer component i can get the current language from array like this

<p v-html="copyrights.en"></p> // --> this will show footer copyright message in english

to get the current page language i have stored it on a locale variable and it returns the current reading language extension (en, fr, it ,.....)

console.log(locale) // returns proper value for example en or de, ...

so now i can choose which message to show on page footer dynamically because i have the current page locale and the multilanguage copyright array with all data i need

so i made a function that will return the correct data

<p v-html="message()"></p> // localized message should be shown here

// this is the function
    message : function(){

      var locale = this.pagesettings.language_id;
      return this.copyrights+locale; // is returning error but copyrights.en is returning correct data

    },

can someone please write the correct code for my dynamic copyright function.

thanx

nhayder left a reply on Sessioned Flash Is Displayed On All Forms On Same Page

i will definitely give it a try

nhayder left a reply on Sessioned Flash Is Displayed On All Forms On Same Page

i'm fully aware of these solutions but my initial question was on how to validate + store + show flashed massage for every form separately without affecting each other???

nhayder left a reply on Sessioned Flash Is Displayed On All Forms On Same Page

login form on the bottom of the page and another one on popup a modal.

nhayder started a new conversation Sessioned Flash Is Displayed On All Forms On Same Page

i have a page with 2 exact forms on same page but they have different css design, unfortunately i'm not being able to differentiate them from each other that resulted to get same validation on the form.

Example when a user fill up a form the laravel is requesting the user to fillup the other page.

<form action="{{route('account')}}" method="POST" enctype="multipart/form-data">

    // email +password

</form>

<form action="{{route('account')}}" method="POST" enctype="multipart/form-data">

    // email +password

</form>

In addition to that, when form data is store the session flash data is also displayed on both form ???

Session::flash('loggedInSuccessMsg');

Any solution for this issue?

09 Jul
1 month ago

nhayder left a reply on Call To A Member Function SetCookie() On Null

ok just found the fix

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class RedirectBlockedAccounts
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (Auth::check()){

            if(Auth::user()->status == 3)
            {

                Auth::logout();
                
                return redirect()->route('errors.block');

            }

        }
        
        return $next($request);

    }
}

nhayder started a new conversation Call To A Member Function SetCookie() On Null

Hey,

I have a middleware that forces blocked users when they are detected,

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class RedirectBlockedAccounts
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {


            if(Auth::user()->status == 3)
            {

                Auth::logout();
                
                return view('errors.block');

            }

        
        return $next($request);

    }
}

the implementation above is returning error

Call to a member function setCookie() on null

is there is a fix for that?

Any Ideas

05 Jul
1 month ago

nhayder left a reply on Customer Command Is Inserting Data Correctly To DB

i can't believe i didn't check the $fillable array, OH

i need to have a very very strong coffee today :-)

Thanks man.

nhayder left a reply on Customer Command Is Inserting Data Correctly To DB

@snapey It's really complicated to explain why at this point, But i'm hoping that you examine the code so i can move on with my project :-).

nhayder left a reply on Customer Command Is Inserting Data Correctly To DB

Why your saying that?? do you have better solution??

nhayder started a new conversation Customer Command Is Inserting Data Correctly To DB

When a user clicks a button on the page i'm running a custom command to feed the database with set of data directly from controller.

in controller, I'm passing some data to command that customize the data like this


    public function addNewWidget(Request $request)
    {
        $request->validate([

            'name' => 'required|string',

            'type' => 'required|int:1,0',

            'page_id' => 'required|integer',

            'installer' => 'required|string',

            'widgetset' => 'required|string',

        ]);

Artisan::call('widget:'.$request->installer.' '.$request->page_id.' '.$wSort.'');

this is the custom command

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Widget;

class contactus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'widget:contactus {pageID} {wSorting}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Soon';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $contactus = Widget::create([

            'name' => 'contactus',
            'page_id' => $this->argument('pageID'),
            'sorting' => $this->argument('wSorting'),
            'poster' => 'placeholder.png',
            'others' => '[email protected]', // this is always NULL in DB laravel is not inserting the email address
            'embed' => 'https://vimeo.com/11254455848',
       
         // ....
        ]);

    }
}


Thankfully, The data is getting inserted as intended, Except the others db field, It's always NULL and Never inserted the intended data => ([email protected]).

This is my migration


        Schema::create('widgets', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->nullable();
            $table->integer('page_id')->unsigned();
            $table->foreign('page_id')->references('id')->on('pages')->onDelete('cascade');
            $table->integer('sorting');
            $table->string('poster')->default('placeholder.png');
            $table->longText('others')->nullable();
            $table->string('embed')->nullable()->default('https://www.youtube.com/embed/Md_YnF09WDY');

        // .... contunue

to keep it short? only the Other db column is always null after running the command from controller where is should insert [email protected] email address,

Can someone see any issue with my code ???

all the best

03 Jul
1 month ago

nhayder started a new conversation Forbidden Access For Portion Of My App From Phone + Tablet

Hi, i need to borbed user to access some part of my app from mobile + tablet devices.

according to my research, a middleware that detects screen size will do that job, is there is a better way on how to do this ???

can you please show some code, ???

01 Jul
1 month ago

nhayder started a new conversation Embedded Youtube Video Keep Playing After Closing Modal

I have a tailwind modal on my app that shows embedded iframe youtube video, when the modal is closed the video keep playing, So

How to stop playing the video at the same time when the modal is closed

<template>

    <div>

        <div v-show="showModal" @click="toggleModal" class="fixed pin z-60 overflow-auto bg-smoke-darker flex font-sans">
            
          <div class="relative w-full max-w-md m-auto flex-col flex animated fadeIn">

            <div class="flex justify-between draggable pb-1 text-white header">
                
                <div></div>

                <div @click.stop="toggleModal" class="cursor-pointer">

                    <i class="fas fa-times text-2xl text-grey-dark hover:text-grey-light"></i>

                </div>

            </div>
                              
            <div class="resp-container">

                <iframe width="560" height="315" src="https://www.youtube.com/embed/8u_3sewnp2w" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

            </div>

          </div>

        </div>

    </div>

</template>

<script>

export default {

    name: 'popup-video-modal',

    props: ['widget', 'media'],

    data () {

        return {

            showModal:false,

        }

    },

    methods: {

        toggleModal : function(){

            this.showModal = !this.showModal;

        },

    }

}
</script>
30 Jun
1 month ago

nhayder left a reply on Vue Is Not Rendering Youtube Video Correctly

Great job, i can see the youtube video loaded correctly on the page???

Thank you

nhayder started a new conversation Vue Is Not Rendering Youtube Video Correctly

on DB i have page URL for a youtube video i need to embed dynamically on the page, I'm using a package that will convert youtube page URL to iframe object, the package is doing its job so there is no issues with that but vue is not being able to render the iframe object on the page.

this is how i'm doing it, Using axios i posting the page URL to laravel end point where the package will return the iframe, this is my component

<template>

      <div @click="requestEmbedManager" v-html="media" class="w-full trans cursor-pointer"></div>
    
</template>

<script>
  
export default {

  props: ['widget', 'wIndex', 'contIndex', 'contID', 'controller'],

  name: 'embed-media',

  data () {

    return {

        media  : '',

    }

  },

  created(){ 

        var url = this.widget.embed;

        axios.post('api/widget/getEmbedMedia', {

            source : url,

        })

        .then(function (response) {

            console.log('From component =>'+response.data);

            this.media = response.data;

        })

        .catch(function (error) {

            return '/media/default/brokenmedia.png';

            Event.$emit('requestAlertEmbededMedia');

        });

  },

  }

}

</script>

it looks like my code is not rendering the iframe object to the page?

can anybody see a problem with my implementation ????

28 Jun
1 month ago

nhayder started a new conversation Vue Component Not Rendering Images Correctly

i'm trying to load images dynamically from dedicated component,

// the media.embed is tested and passing correct data from DB;
<img :src="media(widget.embed)" class="w-full trans cursor-pointer">

in same component i'm updating the image like this

<script>
export default {

  props: ['widget', 'wIndex', 'contIndex', 'contID', 'controller'],

  methods:{

    media : function(url){

        axios.post('api/widget/getEmbedMedia', { 

            source : url,

        })

        .then(function (response) {

            console.log(response.data);
            // returned data is this https://i.ytimg.com/vi/Md_YnF09WDY/hqdefault.jpg

            return response.data; // this should update image

        })

        .catch(function (error) {

            return '/media/default/brokenmedia.png';

            Event.$emit('requestAlertEmbededMedia');

        });

    },

  }

}

</script>

Unfortunately, i can see the correct image path when console.log(resoinse.data) but the image is not getting updated.

Any Ideas???

25 Jun
1 month ago
24 Jun
1 month ago

nhayder left a reply on Change App Default Locale Dynamically

@CRONIX - i already have that implemented but its not working for me because the locale is basically changing in memory not on the actual config.php.

The localization package i'm using basically reads the default language locale from config.php file and compare it with request to determine weather to show or not the default language locale.

i was able to solve the problem simply by changing the config.php default locale value manually and the problem was solved. But its manually not dynamic ???

Not sure how to do it dynamically ???

nhayder left a reply on Change App Default Locale Dynamically

I've been investigating what you wrote and it looks like you are correct.

the App::setLocale($locale); function is changing the locale of the app but not on the config/app.php file (in memory not on local desk).

Unfortunately the package that i'm using need to read the locale value in config/app.php file to render the correct translation on the page.

In this case i think i need to change the locale value on config/app.php dynamically using my a form input then laravel will take care of the reset on first refresh,

BUT not sure how to do that???? how the code will look like ???

NOTE: I'm totally open for better ideas.

nhayder started a new conversation Change App Default Locale Dynamically

i'm using mcamara localization package https://github.com/mcamara/laravel-localization in app an with default language set to english as per default laravel installation config/app.php


/*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

i need to give the user ability to change the default language dynamically using a from, ...

when i don this

    $locale = 'es'; // passed from the form

        Session::put('locale', $locale);

        app()->setLocale(Session::get('locale'));

after submitting the form i can see the locale is changing but mcamara is not picking up the changes, It still seed the default locale = 'en'; as shown above,

not sure if there is another way to do this but i think if i can change the locale in the config/app.php file dynamically and (i mean access the file and change the locale value in php) will do the job.

Is that possible ???? is there is any better way to do this??

Any ideas ?

23 Jun
1 month ago

nhayder started a new conversation Telescope Caching 55 Files Where It Should Cache 1

Just installed telescope on my app.

On my app, i have 4 view composers that will provide a certain data across the entire website. (Theme, Copyright msg, btns data)

// my view composer looks like this

        View::composer('*', function ($view) {
            
            $view->with('btns', Navigation::getNavigationBtns());

        });

        View::composer('*', function ($view) {
            
            $view->with('navbar', Topmenu::getTopMenu());

        });

        View::composer('*', function ($view) {
            
            $view->with('copyright', Copyright::getCopyRights());

        });

        View::composer('*', function ($view) {
            
            $view->with('theme', Theme::getTheme());

        });

these are snippets of individual models

// theme model
    public static function getTheme()
    {
    
        $theme = Cache::rememberForever('theme', function () {

            return static::findOrFail(1);
            
        });
        
        return $theme;
    }


// copyright model
    public static function getCopyRights()
    {

        $copyright = Cache::rememberForever('copyright', function () {

            return static::findOrFail(1);
            
        });

        return $copyright;

    }

// topmenu navigation 

    public static function getTopMenu()
    {
    
        $navbar = Cache::rememberForever('navbar', function () {
        
            return Topmenu::findOrFail(1);
            
        });

        return $navbar;
        
    }

// navigation

    public static function getNavigationBtns()
    {
    
        $btns = Cache::rememberForever('btns', function () {
        
            return Navigation::with('submenu', 'nav_btn_linked_page', 'nav_btn_linked_article')->get();
        });

        return $btns;

    }

keeping in maind that my home page is totally empty except of the cached data above? But yet? i can see from telescope that laravel is hitting these 4 files 55 time, where i was expecting it to hit them only one time, I'm not sure where did i go wrong.

any ideas ???

17 Jun
2 months ago

nhayder left a reply on 2 Mutators In 1 Model ??? Is Posible

@SNAPEY - Yah, that will totally solve the problem.

nhayder left a reply on 2 Mutators In 1 Model ??? Is Posible

@SNAPEY - how to create new mutator with different name can you show some code ?

16 Jun
2 months ago

nhayder left a reply on 2 Mutators In 1 Model ??? Is Posible

@snapey

Sorry about that, i will try to expand on what i'm trying to do,

i'm using a package that will allow me to embed media objects from almost 20 defendant social media sites (youtube, vimeo, instagram, ... etc), for this package to work i made a mutation that converts for example youtube page URL to an embedded iframe object using youtube page url only.

1- First inpoint : so to show youtube video on home i made this mutation

//my first widget.php model mutation is this
1-  the $value basically is  the video standard youtube page url 

    public function getEmbedAttribute($value)
    {
        $info = Embed::create($value); // this converts the URL to embedded video  (proper embedded iframe )

        return $info->code;

    }

the returned object is working fine and i'm being able to get the query with the converted object to display it on the public home page. (blade file)

//Like this
{!! $info->embed !!} // working beautifully 

2- inpoint - app cpanel :

form the app control panel side i have a different controller that hits that same model using another inpoint? obviously i'm getting the same embedded code because of the mutation that i already have on the model.

the difference here is that i don't need the object i just need an representation image of that youtube video. luckelly :-) The package i'm using can provide me with that image like this

// 2nd required mutation to fetch youtube video image

    public function getEmbedAttribute($value)
    {
        $info = Embed::create($value); 

        return $info->image; // this will return the image only (image not code)

    }

The current problem is this (2 in points hitting same model) :

every time i hit the widget.php model im getting the embedded code from public home page or from cpanel inpoint.

what i want to do is : when i hit the widget model from control panel i need to return the image, but when the user hits the front end home page laravel should get me the youtube object as iframe embedded object. unlike what i currently have (always getting the embedded object)

so how can i get 2 different output (image or video) using the same model, i need to let laravel know which mutatio to use according the inpoints that were executed to the run the query (home page or cpanel).

I hope it's clear for you now?

nhayder started a new conversation 2 Mutators In 1 Model ??? Is Posible

Hi, i'm in this situation where i'm accessing same model mutator from 2 different end points, so i need to make different mutator for every endpoint.

// this is the current mutator that i already have it fetches the code DB column

    public function getEmbedAttribute($value)
    {
        $info = Embed::create($value);

        return $info->code;

    }

the other mutator should fetches image instead of code,

    public function getEmbedAttribute($value)
    {
        $info = Embed::create($value);

        return $info->image;

    }

Any ideas ????

14 Jun
2 months ago

nhayder left a reply on Saving Javascript Data On DB (google Analytics + AdSense)

@CRONIX - Interesting, i Will definitely try your solution

nhayder started a new conversation Saving Javascript Data On DB (google Analytics + AdSense)

Hi,

i'm working on new app where my customer need to add Google analytics + adSense dynamically to the header of every page on the website.

I'm using https://github.com/mewebstudio/Purifier to sanitize inputs data, but it looks like the package is now allowing any js script tags after i tried to add them to the package whitelist.

so my question is: How to safely store javascript code in database and render them to blade template.

10 Jun
2 months ago

nhayder started a new conversation Spatie/laravel-sitemap Not Crawling The Site (sitemap.xml Is Empty)

Hi, i'm using spatie/laravel-sitemap https://github.com/spatie/laravel-sitemap to auto-generate sitemap for my app.

as per the documentation i made a command to generate the the site map like this

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;

class GenerateSitemap extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'sitemap:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate the sitemap.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // modify this to your own needs
        SitemapGenerator::create(config('app.url'))

            ->writeToFile(public_path('sitemap.xml'));
            
    }
}

The site map is file is created but its empty so basically it looks like the package is not crawling the app as it should do,

has anybody used this package, How to fix this issue ???

08 Jun
2 months ago

nhayder left a reply on Custom Helper Files Ar Not Working On Shared Hosting Account

@SNAPEY - I made the App like this app, then run composer dump-autoload and it worked

"files" :[
            "app/Helpers/activeAdminSidebar.php", 
            "app/Helpers/messages.php",
            "app/Helpers/isOnline.php"
        ]

@snapey You are awesome :-) thank you man

nhayder left a reply on Custom Helper Files Ar Not Working On Shared Hosting Account

@SNAPEY - Thank you for your note, i checked the files and it looks like they are matching,

// files in Helpers folder are (Helpers/)
1- activeAdminSidebar.php
2- isOnline.php
3- messages.php

on composer.jason i have them declared like this

    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\": "app/"
        },
        "files" :[
            "App/Helpers/activeAdminSidebar.php", 
            "App/Helpers/messages.php",
            "App/Helpers/isOnline.php"
        ]
    },

How i setup the APP on shared hosting is this

outside public_html i have create a folder called demo where i'm storing all laravel files in, as for public folder

i'm using default public_html folder to place laravel public files instead the default public folder that comes with laravel.

also i have updated the index.php files in public_html like this

require __DIR__.'/../demo/vendor/autoload.php';

and 

$app = require_once __DIR__.'/../demo/bootstrap/app.php';

the app is working perfectly on localhost, and on shared account, but every time the app needed any helper functions it breaks,

error sample


Call to undefined function setMainButton() (View: /home/demolinx/demo/resources/views/layouts/sidemenu.blade.php) (View: /home/demolinx/demo/resources/views/layouts/sidemenu.blade.php) (View: /home/demolinx/demo/resources/views/layouts/sidemenu.blade.php)

the setMainButton() function is available on one of the helpers files (activeAdminSidebar.php)

// this is my activeAdminSidebar.php file
<?php

function setMainButton($path){

    return Request::segment(3) === $path ? 'active' : '';

}

function setArrow($path){

    return Request::segment(3) === $path ? 'collapse show' : 'collapse';

}

function activeGroup($path){
    // groupe set
    return Request::segment(3) === $path ? '' : 'collapsed';

}

function setCollapsed($path){
    // collpsed icon function
    return Request::segment(4) === $path ? '' : 'collapsed';

}

function setActive($path){

    return Request::segment(4) === $path ? 'active' : '';

}


Do you see anything in my setup that might cause this type of errors.

nhayder started a new conversation Custom Helper Files Ar Not Working On Shared Hosting Account

i have 3 files added to composer.jason file

        "files" :[
            "App/Helpers/activeAdminSidebar.php", 
            "App/Helpers/messages.php",
            "App/Helpers/isOnline.php"
        ]

The app is fully active on a share hosting account (working perfectly ) except when these 3 files are called withen the app. at that poing im getting this error

Call to undefined function setMainButton() (View: /home/demolinx/resources/views/layouts/sidemenu.blade.php) (View: /home/demolinx/resources/views/layouts/sidemenu.blade.php) (View: /home/demolinx/resources/views/layouts/sidemenu.blade.php)

the setMainButton() is defined in one of the helpers files, Clearly the helper file are not loaded correctly this is why i'm getting these errors.

so my question is? how to reload the helper file on shared hosting using ssh ????

NOTE : composer dump-autoload + composer install is not fixing it for me

24 May
2 months ago

nhayder started a new conversation How To Add New Element To Array

i have this array fetched from db

$contact = Form::find($id);

// returning

{
    "name":"myapp",
    "email":"[email protected]",
    "phone":"+973424242",
    "message":"<p>p<\/p>",
    "updated_at":"2019-05-24 14:58:46",
    "created_at":"2019-05-24 14:58:46",
}

how to add another element to above array ????

"id" :"12",

nhayder left a reply on How To Check Queue Errors

clear, But they are still not moved failed_jobs table yet, I can see them on the jobs table with attempts of 255.

so how to check the error at this point, Before the are moved to failed_jobs table and after exceeding all attempts

nhayder started a new conversation How To Check Queue Errors

i have a contact form that queue's the emails using event & listener, the jobs keeps on failing to execute and i can see any thing to help me identify the error?

How to debug queued jobs when they fail?? there should be something that through error so i can fix it

how to get the error message for failed jobs