atfinho

atfinho

Member Since 1 Year Ago

Experience Points 1,880
Experience Level 1

3,120 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 2
Lessons
Completed
Best Reply Awards 0
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.

11 Sep
6 days ago

atfinho started a new conversation Many To Many Relationship

Hey guys I saw many examples about many to many relationships.. most of them use attach() method

so for example if I have Product ,Order Tables with pivot table OrderProduct..

$order=Order::find(1);
$order->products()->attach(1);

This will normally attach product 1 to order 1..

what about if I have extra fields in OrderProduct for instance " quantity" ?

how can I update it using attach() ?

07 Sep
1 week ago

atfinho left a reply on Api Tips

Thank you but I mean it has the same concept like pusher,laravel echo..etc ? Because I want to use it for mobile..

atfinho left a reply on Api Tips

But as I know they are paid services..

atfinho started a new conversation Api Tips

Hey guys I was recently involved in a laravel project which is also connected to mobile applications through web services.. anyway I was in contact with the mobile developer and he asked me if there is a way that prevents him for making multiple api calls..

Basically he wants a real time tool that alerts him that something was changed in the database so at that time he will make a call otherwise he keeps retrieving from local storage..

I don't know if you have any idea about a free service that generates that..

Thank you in advance !

06 Sep
1 week ago

atfinho left a reply on Error In Registering A Simple Vue Component With Laravel

@tykus I just want it to be just in a specific blade , I mean I don't need it anywhere else

atfinho left a reply on Error In Registering A Simple Vue Component With Laravel

it worked by simple changing the vue tag from

  <ExampleComponent> </ExampleComponent>

//to

    <example-component> </example-component>

is there any convention about naming components in vue guys ?

atfinho left a reply on Error In Registering A Simple Vue Component With Laravel

@tykus can you explain to me what's wrong with it ?

atfinho left a reply on Error In Registering A Simple Vue Component With Laravel

still always getting the same error :(( I don't know why ! I used vue before in another project but for this one it's firing this error...

atfinho started a new conversation Error In Registering A Simple Vue Component With Laravel

Hey guys I'm trying to register a vue component in laravel blade and I'm getting this error

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option

This is app.js

require('./bootstrap');


window.Vue = require('vue');
import Vue from 'vue'
import ExampleComponent from './components/ExampleComponent.vue'

Vue.component('ExampleComponent', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app',
    components: { ExampleComponent },


});

This is my ExampleComponent.Vue

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Dashboard Component</div>

                    <div class="card-body">
                        I'm an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
    
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

And this is my blade


<div class="content-wrapper" id="app">

    <section class="content-header">

        {{ Breadcrumbs::render('addCustomProduct',$company) }}
    </section>

    <section class="content" style="margin-top:20px;">
        <div class="row">
            <div class="container">
                <ExampleComponent> </ExampleComponent>


            </div>
        </div>

    </section>

</div>

I don't know what's wrong is happening :(

atfinho left a reply on Production Vs Local Url In Laravel Vue Js

can you give me an example ?

atfinho started a new conversation Production Vs Local Url In Laravel Vue Js

Hey guys I would like to know when you build any content with laravel & vue how do u set Application url for local and production ?

for example in laravel we have .env and we have APP_ENV.. what about when I use vue js components ?

05 Sep
1 week ago

atfinho started a new conversation PHP Version XAMPP

Hey guys , I'm using ubuntu 16.04

I recently installed a laravel project which one of its packages require php 7.2.. and my installed XAMPP has 7.1.30 PHP version so I reinstalled a new one..

phpinfo() shows me 7.2.22

PHP -v shows me 7.1.3

how can I always point on the first one ??

06 Aug
1 month ago

atfinho left a reply on Virtual Host Set Up

@coachthem always the same :(((

atfinho started a new conversation Virtual Host Set Up

Hey Guys

I'm trying to set up a virtual host for my project I'm using Ubuntu 16.04

I'm facing 2 issues right now

first , I switched to this directory /etc/apache2/sites-available/

I simply copied **000-default.conf** to another file example.conf

then

sudo a2ensite example.conf to enable the new file

sudo a2dissite 000-default.con to disable the old one

inside example.conf I have

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.test
    ServerAlias www.example.test
    DocumentRoot /opt/lampp/htdocs/pixmania-front-v2/Apps/Pixmania/Front/htdocs/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

I edited /etc/hosts

127.0.0.1 example.test

right now when I type example.test on browser it redirects me to example.test/dashboard

couldn't know why...

Later on , I tried a solution that I found on stackoverflow which is to comment out **httpd-vhosts.conf ** in **httpd.conf ** this solution redirects me to 403 error on localhost !

I hope you can help me!

05 Aug
1 month ago

atfinho left a reply on Push To Array Without Add Key

@tykus I have a table of posts and a checkbox beside every record. so whenever I hit the checkbox it stores the id in deleteMultiple array then I pass all the ids to laravel in order to delete them.. I used map to track the id when I uncheck the input and remove it from the array

atfinho started a new conversation Push To Array Without Add Key

Hey guys I would like to know how can I remove keys from an array .. For example this is an array : ['0' => 'value 0 ' , '1' =>'value 1 ']

I want just to display ['value 0', 'value 1' ]

I have this array


    data(){

     return{

     deleteMultiple:[]
            
}
    },

Then I'm trying to gather a specific ids to delete them later

    addDeleteItems(id,event){
                        if (!event.target.checked) {
                        let i = this.deleteMultiple.map(item => item.id).indexOf(id) // find index of your object
                        this.deleteMultiple.splice(i, 1) // remove it from array
                          }
                          else{
                            alert(id);
                              this.deleteMultiple.push(id);

                          }
                       },

I'm getting always that output even though I use push...

02 Aug
1 month ago

atfinho started a new conversation Laravel Echo Events Render Issue

Hey guys , I'm trying to display event coming from pusher in my vuejs app so I just added this following code in one of my components

 mounted() {

        var channel = Echo.channel('Post');
        channel.listen('event', function()  {
            alert('hi');
        });


    },

when I refresh the page and check pusher debuger I can see Channel Post occupied.. I send data from there but nothing displays ! no errors in console..

This is my event

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class CreatePost implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

   public $post;

   
   
    public function __construct($post)
    {
         $this->post=$post;
    }

    public function broadcastOn()
    {
        return new Channel('Post');
    }

    public function broadcastAs()
    {
        return 'event';
    }
}

Added the code below in bootstrap.js

import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: mykey,
    cluster: 'eu',
    encrypted: true
});

in my env file I changed broadcast=> pusher

couldn't figure out what's wrong here...

atfinho started a new conversation Send Event To Pusher ( Laravel 5.7)

Hey guys I'm trying to send an event to pusher but it's not working , it's always displaying " Waiting for events..."

here is my code

Routes:

Route::get('/pusher', function() {
    event(new App\Events\CreatePost('Hi there Pusher!'));
    return "Event has been sent!";
    });


.env:

PUSHER_APP_ID=app_id
PUSHER_APP_KEY=app_key
PUSHER_APP_SECRET=app_secret
PUSHER_APP_CLUSTER=eu


Event:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class CreatePost implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

   public $post;

   
   
    public function __construct($post)
    {
         $this->post=$post;
    }

    public function broadcastOn()
    {
        return new Channel('Post');
    }
}



I added my credentials to .env file changed BROADCAST_DRIVER -> pusher

ran php artisan config:cache for many times.. it doesn't work

30 Jul
1 month ago

atfinho started a new conversation Router Link Not Working

Hey guys I'm trying to display just example components on my website , I set up vue router and I created routes on app.js

in the blade routes don't work ( console show no errors)

this is app.js

window.Vue = require('vue');

import Vue from 'vue'
import VueRouter from 'vue-router'
import Dashboard from './components/Dashboard.vue'
import Profile from './components/Profile.vue'

Vue.use(VueRouter)



let routes = [
    { path: '/dashboard', component: Dashboard },
    { path: '/profile', component: Profile }
]



const router = new VueRouter({
    routes // short for `routes: routes`
});




Vue.component('Dashboard', require('./components/Dashboard.vue'));
Vue.component('Profile', require('./components/Profile.vue'));


const app = new Vue({
    router
});

I wrapped all my blade vue content with this div

<div class="wrapper" id="app">

</div>

this is the part where I implemented router-links

<nav class="mt-2">
    <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">

        <li class="nav-item">
            <router-link to="/dashboard" class="nav-link">
                <i class="nav-icon fas fa-tachometer-alt"></i>
                <p> Dashboard </p>
            </router-link>
        </li>

        <li class="nav-item has-treeview menu-open">
            <a href="#" class="nav-link active">
                <i class="nav-icon fas fa-tachometer-alt"></i>
                <p>
                    Starter Pages
                    <i class="right fas fa-angle-left"></i>
                </p>
            </a>

        </li>

        <li class="nav-item">
            <router-link to="/profile" class="nav-link">
                <i class="nav-icon fas fa-user"></i>
                <p>
                    Profile

                </p>
            </router-link>
        </li>

        <li class="nav-item">
            <a href="#" class="nav-link">
                <i class="nav-icon fas fa-power-off"></i>
                <p>
                    Logout

                </p>
            </a>
        </li>

    </ul>
</nav>

and below I have

 <div class="content" >
      <div class="container-fluid" >
      <router-view></router-view>
      </div>
    </div>

whenever I click on the items nothing happened... how can I fix this ??

atfinho left a reply on [Vue Warn]: Unknown Custom Element: <router-view>

Thank you so much , I spent almost two hours struggling to resolve it

25 Jun
2 months ago

atfinho left a reply on Approach For A Multi Step Form

@SNAPEY - Thank you for the trick.. do you think it's an optimized solution to call the server for data validation and to get back from a step to a previous one ?

atfinho left a reply on Error Message When Trying To Register A User - "The Email Has Already Been Taken"

"The email has already been taken" the error is obvious.. in your backend validation you set unique email for every user..

  'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],

20 Jun
2 months ago

atfinho started a new conversation Laravel Breadcrumbs

Hey guys I'm using laravel-breadcrumbs package

I would like to pass a dynamic value as a parameter to another breadcrumb something like

Home / {company} / Text

The code below gives me the company name

Breadcrumbs::for('detail', function ($trail, $company) {
    $trail->parent('company');
    $trail->push($company->name, route('showHome', $company));
});

I tried to get it as a parent to generate the new one

Breadcrumbs::for('store', function ($trail, $company) {
    $trail->parent('detail',$company->name);
    $trail->push('Magasins', route('showStores',$company));
});


This gives me an error of non object for the detail breadcrumb

How can I fix this ?

atfinho started a new conversation Jquery Prepend Issue

Hey guys I'm using jquery

I've a div that includes some inputs, I want to dupplicate it whenever I hit a button.. when the new content is dupplicated I want to add on the top of it another content ( X button) to give option to delete it but it didn't work... I tried using prepend.. here is my code

<script>
$('document').ready(function(){

  var newProduct=$('.box-color').html();
  var newButton=$('.clicked').html();
$('.clicked').click(function(){
// this is content that has to be inserted in the top of dupplicated one
var html="";
html+= '<div class="box-tools pull-right">';
html+='<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>';
html+=' <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>';
html+='</div>';

$(newProduct).prepend(html);

$('.box-color').append(newProduct);


});

});

</script>
18 Jun
2 months ago

atfinho left a reply on Manual Login

Thank you guys for all your responses the problem was coming from ' web' middleware which wasn't included beside my custom middleware.. so for that reason Auth::check() was always returning false..

17 Jun
3 months ago

atfinho started a new conversation Manual Login

Hey Guys I'm trying to make a manual login in my application so I created a middleware to protect some routes from unauthorized user when I login it always redirects me back to the same page ..

I created isAuth middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class isAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()){
        return $next($request); }
        else{
           return redirect()->route('showLogin');
        }
    }
}

I have the login function below

      public function handleLogin(Request $request)
    {
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            Auth::user();
            if (Auth::check()) {

                alert()->success('Succés!', 'Bienvenue!');
                return redirect()->route('showHome');
            } else {
                alert()->error('Oups!', 'Email ou Mot de passe incorrect !');
                return redirect()->back();
            }

        }

    }

this is Home Page route ( redirection after login)

Route::group(['module' => 'General', 'middleware' => ['isAuth'], 'namespace' => 'App\Modules\General\Controllers'], function() {

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


22 May
3 months ago

atfinho started a new conversation Auth Info Required To Subscribe To Private-channel Pusher JS

Hey Guys I need your help since I've posted this for couple of times and didn't get a useful answer ,I'm using pusher js and I'm trying to listen for a private channel.. I've this code below in my react js app

 componentDidMount() {
 
if(localStorage.getItem('user')){
  
  var pusher = new Pusher('23525de46fdea6e17af3', {

    authEndpoint: 'http://localhost/crud-app/public/api/broadcast/authorize',
    cluster: 'eu',
    encrypted: true,
    auth:{
        headers:{
          'Accept':'application/json',
          'Authorization': `Bearer ${localStorage.userToken}`
        }
      }
  });
  const id=JSON.parse(localStorage.getItem('user')).id
  
  const channel = pusher.subscribe('private-post'+id);
    channel.bind('App\Events\NewPost', data => {
alert('data recieved !');

})

}




  }

For the back side

I have this function below for authentication

public function handleAuthorizeUser(Request $request){


    $user = auth()->user();
    if ($user) {
        $pusher = new \Pusher(config('broadcasting.connections.pusher.key'), config('broadcasting.connections.pusher.secret'), config('broadcasting.connections.pusher.app_id'));
        $auth=$pusher->socket_auth($request->input('channel_name'), $request->input('socket_id'));
        return response()->json([$auth]);
    }else {
        header('', true, 403);
        echo "Forbidden";
        return response()->json(['statut'=>403]);
    }


}

This is the event that I'm firing

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewPost implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

   public $post;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($post)
    {
        $this->post=$post;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('post'.$this->post->user_id);
    }
}

and finally this is the content inside channels.php


Broadcast::channel('post.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

I don't see any error in the console ! except that in pusher dashboard whenever I refresh the page I get Auth info required to subscribe to private-post1

Thank you in advance

atfinho left a reply on Subscribe To Private Channels Pusher

@CORBOSMAN - I'm using a seperated react js so I could not get access to that {{csrf_token }}, it will just displays me the same string.. I could not get it from controller as well ://

atfinho started a new conversation Subscribe To Private Channels Pusher

Hey guys I'm trying to subscribe to private channels in pusher and I'm using react js & Laravel after reading some of their documentation it was mentioned that private channels need authentication and I should pass 'X-CSRF-Token' when I listen to this kind of channels + adding a prefix before the name of channel " private " ..

Anyway in my front side this is my code to listen for private channels


 componentDidMount() {
 
    const pusher = new Pusher('23525de46fdea6e17af3', {
   
      auth: {
        headers: {
          auth: { 
            headers: { 
              'X-CSRF-Token': localStorage.userToken 
            }
           }
        }
      },
      cluster: 'eu',
      encrypted: true
    });
    const channel = pusher.subscribe('private-channel');
    channel.bind('App\Events\NewPost', data => {

alert();
   
   }

 localStorage.userToken 

the code above gives me access to user token that I get from passport when I authorize any user to my app..

this throws an error of : POST http://localhost:3000/pusher/auth 404 (Not Found)

I tried also to pass csrf_token from controller doing something like this

 $token=csrf_token()
// pass it to response

$token returns always null

this is my event code

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewPost implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

   public $text;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($text)
    {
        $this->text=$text;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel');
    }
}


I don't know how to fix this ..

I hope someone can help me to get through it thank you in advance

21 May
3 months ago

atfinho left a reply on Sending Mail Issue

adding the application password to " Mail_password" in env was the solution... I kept the same configurations for the others..

atfinho left a reply on Sending Mail Issue

@DIPAKRATANIAGILE - I just generated an app password as it's mentioned there.. I also changed the mail_port and encryption as you told me.. I keep get the same erro :(

I tried php artisan config:cache / php artisan cache:clear restarted the server.. always the same :((

atfinho started a new conversation Sending Mail Issue

Hey guys , I'm trying to send an email with smtp but I'm keep getting an error

Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators. Authenticator LOGIN returned Expected response code 235 but got code "534"

even though I allowed : less secure apps , 2 steps validation, unlocked captcha

but the error keeps persist !

this is the function

 $data = array('name'=>"Name");
      Mail::send('emails.welcome', $data, function($message) {
         $message->to('[email protected]', 'Tutorials Point')->subject
            ('Laravel HTML Testing Mail');
         $message->from('[email protected]','Sender');
      });
      echo "HTML Email Sent. Check your inbox.";

and this my .env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail
MAIL_PASSWORD=mypass
MAIL_ENCRYPTION=tls
20 May
3 months ago

atfinho left a reply on Laravel & Pusher Instruction

@CRNKOVIC - I tried with this following code.. I created a new app... now I don't get anything even when I hit " send event" from pusher.. :/


window.Echo = new Echo({
  broadcaster: 'pusher',
  key: '23525de46fdea6e17af3'
});

window.Echo.channel('my-channel')
.listen('NewPost', (e) => {
console.log(e)
});

  }

atfinho left a reply on Laravel & Pusher Instruction

@CRNKOVIC - so I should set up laravel echo in my react app ?

atfinho started a new conversation Laravel & Pusher Instruction

Hey guys I'm new to laravel & pusher combinaison ,I would like to know how can I automatically get my data from pusher when I fire an event in laravel

I'm using react js in front end

here I send an event when I add a new post

  $post=Post::create([
            'title'=>$request->input('title'),
           'description'=>$request->input('description'),
            'user_id' =>$request->input('userId') 
        ]);


        $text="New Post has been added !";
        event(new NewPost($text));



this is NewPost event

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewPost implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

   public $text;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($text)
    {
        $this->text=$text;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('my-channel');
    }
}



This is my code in react to render the data

  componentDidMount() {
  
    const pusher = new Pusher('23525de46fdea6e17af3', {
      cluster: 'eu',
      encrypted: true
    });
    const channel = pusher.subscribe('my-channel');
    channel.bind('NewPost', data => {
      alert(JSON.stringify(data.text))
  
      this.setState({ notifications: JSON.stringify(data.text)});
    });

  }


I can see the data in pusher dashboard succesfuly , but this data doesn't automatically show up in my page only when I hit " send event" button ...

how can I do it automatically after submitting the post?

16 May
4 months ago

atfinho started a new conversation Upload Pdf File Base64

I'm trying to upload a pdf file encoded in base64

the file got uploaded but it's not accessible " PDF document is damaged"

this is my code :

 public function handleUploadPdf(Request $request){

    $image = $request->input('image');  // your base64 encoded
    $image = str_replace('data:application/pdf;base64,', '', $image);
    $image = str_replace(' ', '+', $image);
    $imageName = str_random(10).'.'.'pdf';
    \File::put(public_path(). '/images/' . $imageName, base64_decode($image));

    return response()->json(['status'=>200]);

  }

what is causing this issue ? thank you in advance

atfinho left a reply on Save File With Original Extension

Thank you guys

I just added this following code and it worked properly

 /**Extract file extension */
        $img = explode(',', $image);
        $ini =substr($img[0], 11);
        $type = explode(';', $ini);
echo $type[0]
        /** $type[0] type image */

atfinho started a new conversation Save File With Original Extension

Hey guys

I'm trying to upload an image via restful api.. the code below works only when image is " PNG " .. otherwise I couldn't access to it.. how can I upload any image no matter is the extension?

        $image = $request->input('image');  // your base64 encoded
        $image = str_replace('data:image/png;base64,', '', $image);
        $image = str_replace(' ', '+', $image);
        $imageName = str_random(10).'.'.'png';
        \File::put(public_path(). '/images/' . $imageName, base64_decode($image));

Thank you in advance !

15 May
4 months ago

atfinho started a new conversation Upload Image Base_64 Format Issue

I'm trying to upload an image using Intervention Image package but I'm always getting the following error

** Intervention\Image\Exception\NotReadableException: Unable to init from given binary data. **

This is my upload code

this is the image string : data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD…d2dFZfOcMOByDWtESycgDHHSsa0xtCgcetagiWRQefSrMWf/Z"

        if($request->get('image'))
        {
           $image = $request->get('image');
           $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
           $base=base64_decode($image);
           \Image::make($base)->save(public_path('images/').$name);
         }
 
        return response()->json(['status'=>200,'img'=>$request->get('image')]);

Any help ?

atfinho started a new conversation Restful Api Laravel + React JS

Hey guys I'm trying to get a user data from an api using react connected to my laravel back end app

the issue is I'm always getting '401 unauthorized" even though when I test my api on postman it works correctly and I passed the same headers in the api call

I didn't know how to fix that

This is my route :


Route::group(['prefix'=>'api','module' => 'User','middleware' => ['auth:api','CORS'], 'namespace' => 'App\Modules\User\Controllers'], function() {
    Route::get('/get/user','[email protected]');
});

This is the function

public function handleGetUser(){
    return response()->json(['statut'=>200,'user'=>Auth::user()]);

}

This is CORS middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: * ');
        header('Access-Control-Allow-Headers: Content-type, X-Auth-Token, Authorization , Origin ');
        return $next($request);
    }
}


This is the call in my react app

export const getProfile = () => {

    axios.get(`http://localhost/crud-app/public/api/get/user`, 
    {   'Accept': 'application/json', 
        'Content-Type': 'application/json',
          'Authorization' : `Bearer ${localStorage.userToken}` })
    .then(res => {
      console.log(res);
  
    })  
}

09 May
4 months ago

atfinho left a reply on Where Are You All From?

Bizerte - Tunisia

04 May
4 months ago

atfinho left a reply on Restful Api Middleware

@JAEC86 - I return a specific status instead of view redirection ?

atfinho started a new conversation Restful Api Middleware

Hey guys I've a question.. When I'm building a full application with laravel and I have multi auth system ( normal user,admin..etc) So normally in users table I have a specific column to filter between them.. ( restrict normal user from access to dashbard for example) So all of that would be done using middlewares..

Let's say I'm now developping an app with another framework in front ( react ,angular) so do I still need middlewares in the back for multi auth ?? Thank you!

22 Mar
5 months ago

atfinho started a new conversation Multi Level Relationships Dbquery

Hey guys , I've an issue that I couldn't access to multi level relationships in dbquery

I have already this query that works properly the idea is I have one table called " car_maintenance" that is related to " cars" Table

car hasMany car_maintenance

I want to display sum of a field inside " car_maintenance" table called " total_price" for every car_id

                                        $getBookingDays= DB::table('bookings')
                                         ->groupBy('bookings.car_id')
                                         ->groupBy('cars.model')
                                         ->groupBy('cars.daily_price')
                                         ->groupBy('car_manufacturers.name')
                                         ->join('cars','bookings.car_id','cars.id')
                                         ->join('car_manufacturers','cars.car_manufacturer_id','car_manufacturers.id')
                                       ->select([
                                        'cars.model','car_manufacturers.name',
                                        DB::raw('sum(DATEDIFF(bookings.to,bookings.from)) as bookingDays'),
                                        DB::raw('365-sum(DATEDIFF(bookings.to,bookings.from)) as parkingStay'),
                                        DB::raw('cars.daily_price*sum(DATEDIFF(bookings.to,bookings.from)) as gains'),
                                        ])->get();

whenever I add the line below , I get a double value for "booking days "

 ->leftJoin('car_maintenance','car_maintenance.car_id','=','cars.id')

I hope you're getting what I mean..

thank you in advance

atfinho left a reply on Sum Returns Double Value

@ETTORE - do you mean seperate the queries then join them ?

atfinho left a reply on Sum Returns Double Value

@MUNAZZIL - this throws an error unknowen column "="