atfinho

atfinho

Member Since 1 Year Ago

Experience Points 1,240
Experience Level 1

3,760 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.

25 Jun
3 weeks 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
4 weeks 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
1 month 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
1 month ago

atfinho started a new conversation Manual Login

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

I create 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
1 month 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 left a reply on Subscribe To Private Channels Pusher

@CORBOSMAN - ``` let token = document.head.querySelector('meta[name="csrf-token"]')

this just displays me " csrf_token()" in the console since I'm using a seperated react js app I think...
is there a way to pass it from controller directly ?

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

I don't know how to fix this ..

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

21 May
1 month 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 !

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
1 month 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
2 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..

        $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
2 months ago

atfinho started a new conversation Upload Image 64_format Problem

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 I passed the same headers in the api call

I didn't know 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 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
2 months ago

atfinho left a reply on Where Are You All From?

Bizerte - Tunisia

04 May
2 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.. ( retrieve 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
3 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 "="

atfinho left a reply on Sum Returns Double Value

@ETTORE - I tried that as well but still facing the same issue :(

atfinho left a reply on Sum Returns Double Value

@ETTORE - yes exactly it returns value*2 for every record... it seems something is joined twice but I couldn't figure out

atfinho started a new conversation Sum Returns Double Value

Hey guys , I have this query below where I want to get sum total_price value from a table called " car_maintenance" which is related " bookings" the problem is that sum returns me double value..

this is the query

$filter=DB::table('bookings') ->groupBy('cars.model') ->groupBy('cars.daily_price') ->join('cars','bookings.car_id','=','cars.id') ->leftJoin('car_maintenance','car_maintenance.car_id','=','bookings.car_id') ->select('cars.model', 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'), DB::raw('sum(car_maintenance.total_price) as losts')) ->get();

Thank you

13 Mar
4 months ago

atfinho left a reply on How To Select Specific Columns And Get Related Relationships

@EDOC - Thank you bro ! That's exactly what I want!

atfinho left a reply on How To Select Specific Columns And Get Related Relationships

I want just to get just name of users + their posts using ( with )

atfinho started a new conversation How To Select Specific Columns And Get Related Relationships

Hey Guys I want to do something like User::pluck('name')->with('posts') but it seems this doesn't work.. how can I do it ?

11 Mar
4 months ago

atfinho left a reply on Submit Payouts Directly To Debit Cards

https://www.paypal-community.com/t5/About-Settings/can-i-send-and-receive-payments-in-tunisia/td-p/976310

the problem is not coming from paypal itself it's from the regulations here... I can only send money not recieve :// I think it's quite complicated honestly...

atfinho left a reply on Submit Payouts Directly To Debit Cards

Thank you for your answer Yes I can take in charge that with my own logic but the issue is with paypal and other payment services that are not allowed in my country to withdraw money.. I can only send payouts ( shopping..etc) ... So Im looking for a trick to get through this...

atfinho started a new conversation Submit Payouts Directly To Debit Cards

Hey Guys I want to add payment functionnality to my website The strategy is User A pay User B and website get commission I'm facing an issue with payment gateways which are not accessible in my country to withdraw money so I'm only able to make payouts.. is there a script or something that allows me to pay directly to a debit card ?

03 Mar
4 months ago

atfinho started a new conversation Payments With Stripe/paypal

Hey Guys I would like to develop a website where I can let users send money to each other.. is this possible using stripe ? what is the simplest way to implement it thank youu