BezhanSalleh

BezhanSalleh

Member Since 4 Years Ago

Kabul

Experience Points
92,770
Total
Experience

2,230 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
640
Lessons
Completed
Best Reply Awards
42
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

Level 19
92,770 XP
Apr
10
1 month ago
Activity icon

Awarded Best Reply on Passing Locale To All Queued Mails?

@splendidkeen you need to check your logic for when changing languages, whether it changes the language for the session or not. If you have a middleware you need to include it on the routes or it depends on how you are handling the language change because this solution works just fine for setting the locale or language for the jobs or mails...

so basically it would be somthing like this. LanguageSwitcher Middleware


namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;

class LanguageSwitcher
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(session()->has('locale')){
            app()->setLocale(session()->get('locale'));

            Carbon::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}

Register in the app\Http\Kernel.php

    protected $middlewareGroups = [
        'web' => [
		...
            \App\Http\Middleware\LanguageSwitcher::class,
		...
    ];

LanguageSwitcherController.php

class LanguageSwitcherController extends Controller
{
    public function switch($locale){

        session()->put('locale', $locale);
        session()->save();
        return back();
    }

}

Route

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

blade/html snippet - you can change it based on your design...

<div class="btn-group btn-collection btn-icon-group mr-3">
    <a class="btn btn-secondary" href="/locale/en">EN</a>
    <a class="btn btn-secondary" href="/locale/es">ES</a>
</div>

if you have this setup for changing the language this trait for the jobs would work just fine.

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen it doesnt matter if i'm sending an email or not i'm getting the correct locale or language inside the handle method of the job so your issue is somewhere else in your code... maybe remove the default language variable from your middleware and set your default locale inside config/app.php -> locale. anyways delete your post and maybe repost it. don't want someone else going in circles as well. cheers.

just last try can i see the controller code and its route ... caz my test works and the issue is somewhere in your code.

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen here i put my test code in this repo you can clone it and test it and make the necessary adjustments in your own code. https://github.com/bezhanSalleh/get-locale-inside-job-class best of luck

Activity icon

Replied to REST API - Lumen Or Laravel

depends on the application you are building... the performance and how much load its gonna handle... if its just API you should go with lumen because its faster and can handle 1900 request per second.

Activity icon

Replied to Apply Where Condition Based On Value In Table Column

@engrlaravel

$template = ReportTemplate::where('deleted_at', null)
  ->where('id',$request->input('template_id'))
  ->where(function($query) use ($request) {
      $query->where('template_type','user')
         ->where('created_by',$request->input('user_id'));
 })
->where('company_id',$request->input('company_id'))
->first();
Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen see the update! and test it.. it will work if everything is setup the way its suppose to

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen inside the job do logger('lang from session'.session('lang')) and i think you need to adjust the Language middleware logic as well.

        if($request->has('lang')) {
            $lang = $request->lang;
            if(array_search($lang, $this->languages) === false) {
                $lang = $this->default;
            }
            session()->put('lang', $lang);
            session()->save();
        }

        if(Auth::check()){
            if(auth()->user()->language_id == 2) 
            {
                session()->put('lang', 'es');
                session()->save();
            }
            else{
                session()->put('lang','en');
                session()->save();
            }
        }
          
        Carbon::setLocale(session()->get('lang'));
        app()->setLocale(session()->get('lang'));

        return $next($request);

you don't need the trait anymore you can just do this

Mail::to($this->user->email)
        ->locale(app()->getLocale())
        ->send($email);

i believe you will be good to go...

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen you need to check your logic for when changing languages, whether it changes the language for the session or not. If you have a middleware you need to include it on the routes or it depends on how you are handling the language change because this solution works just fine for setting the locale or language for the jobs or mails...

so basically it would be somthing like this. LanguageSwitcher Middleware


namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;

class LanguageSwitcher
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(session()->has('locale')){
            app()->setLocale(session()->get('locale'));

            Carbon::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}

Register in the app\Http\Kernel.php

    protected $middlewareGroups = [
        'web' => [
		...
            \App\Http\Middleware\LanguageSwitcher::class,
		...
    ];

LanguageSwitcherController.php

class LanguageSwitcherController extends Controller
{
    public function switch($locale){

        session()->put('locale', $locale);
        session()->save();
        return back();
    }

}

Route

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

blade/html snippet - you can change it based on your design...

<div class="btn-group btn-collection btn-icon-group mr-3">
    <a class="btn btn-secondary" href="/locale/en">EN</a>
    <a class="btn btn-secondary" href="/locale/es">ES</a>
</div>

if you have this setup for changing the language this trait for the jobs would work just fine.

Activity icon

Replied to Apply Where Condition Based On Value In Table Column

$template = ReportTemplate::where('deleted_at', null)
        ->where('id',$request->input('template_id'))  
        ->where(function($query) use ($request) {
                    if ($query->type == 1) {
                        return $query->where('created_by',$request->input('user_id'));
                    }               
                })           
        ->where('company_id',$request->input('company_id'))->first();
Activity icon

Awarded Best Reply on Update Other Table With Relationships

@feelsonix PostController.php -- update method

    public function update(Request $request, $id)
    {

        $this->validate($request, array(
                'title' => 'required|max:255',
                'slug'  => 'required',
                'category_id' => 'required|integer',
                'body'  => 'required'
        ));

        // Validate the data
        $post = Post::find($id);
        $categories = Category::pluck('name','id');


        $post->title = $request->input('title');
        $post->slug = $request->input('slug');
        $post->category_id = $request->input('category_id');
        $post->user_id = Auth::id();
        $post->body = $request->input('body');

        if ($request->hasFile('featured_img')) {
            // Ajoute la nouvelle photo
            $image = $request->file('featured_img');
            $filename = time() . '.' . $image->getClientOriginalExtension();
            $location = public_path('img/' . $filename);
            Image::make($image)->fit(1200, 500)->save($location);

            $oldFilename = $post->postImage->url;

            $post->postImage()->createOrUpdate([
                'post_id' => $post->id
            ],[
                'url' => $filename
            ]);
            // Efface l'ancienne photo
            Storage::delete($oldFilename);

        }

        $post->save();

        Session::flash('success', "L'article à été correctement mis à jour.");

        return redirect()->route('posts.index');
    }

PostImage.php -- model

class PostImage extends Model
{
    protected $table = 'image';

    protected $fillable = ['url','post_id'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Post.php -- model

class Post extends Model
{
    protected $fillable = ['title','description','order'];

    public function postImage()
    {
        return $this->hasOne(PostImage::class);
    }
}

adjust the namespace for the models and migrations and you would be good to go... but you need some extra work to delete the image from storage and if save fails you could run the code for update inside a transaction. anyways good luck.

Activity icon

Replied to Custom Artisan Command That Calls Other Commands?

@catinodev haha no problem, happens to the best of us.

Activity icon

Awarded Best Reply on Custom Artisan Command That Calls Other Commands?

@catinodev sure you can, so it says in the documentation https://laravel.com/docs/7.x/artisan#calling-commands-from-other-commands just make sure all your commands are properly registered.

Activity icon

Replied to Custom Artisan Command That Calls Other Commands?

@catinodev sure you can, so it says in the documentation https://laravel.com/docs/7.x/artisan#calling-commands-from-other-commands just make sure all your commands are properly registered.

Activity icon

Replied to Update Other Table With Relationships

@feelsonix you are most welcome ... mark it as answered if it helped so others can ignore it and if others want it they could refer to it.

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen yes you can use the middleware but it might takes some time and knowing how but just revert the changes you made till now and create a trait that returns the current language or locale based on the session and use that trait on your jobs...

trait SetJobLocaleForMails
{
   public function getCurrentLocale()
   {
	 if( session()->has('lang') && session('lang') === 'es') 
         {
		return 'es';
	 }
	
         return 'en';
   }
}

Now based on where you put the trait - normally a folder named Traits but here is how your jobs would look like from now on

use SetJobLocaleForMails;
protected $user;

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

/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{
    $email = new Verify($this->user);
    
    Mail::to($this->user->email)->locale($this->getCurrentLocale())->send($email);
} 

let me know how it goes...

Activity icon

Replied to Update Other Table With Relationships

@feelsonix PostController.php -- update method

    public function update(Request $request, $id)
    {

        $this->validate($request, array(
                'title' => 'required|max:255',
                'slug'  => 'required',
                'category_id' => 'required|integer',
                'body'  => 'required'
        ));

        // Validate the data
        $post = Post::find($id);
        $categories = Category::pluck('name','id');


        $post->title = $request->input('title');
        $post->slug = $request->input('slug');
        $post->category_id = $request->input('category_id');
        $post->user_id = Auth::id();
        $post->body = $request->input('body');

        if ($request->hasFile('featured_img')) {
            // Ajoute la nouvelle photo
            $image = $request->file('featured_img');
            $filename = time() . '.' . $image->getClientOriginalExtension();
            $location = public_path('img/' . $filename);
            Image::make($image)->fit(1200, 500)->save($location);

            $oldFilename = $post->postImage->url;

            $post->postImage()->createOrUpdate([
                'post_id' => $post->id
            ],[
                'url' => $filename
            ]);
            // Efface l'ancienne photo
            Storage::delete($oldFilename);

        }

        $post->save();

        Session::flash('success', "L'article à été correctement mis à jour.");

        return redirect()->route('posts.index');
    }

PostImage.php -- model

class PostImage extends Model
{
    protected $table = 'image';

    protected $fillable = ['url','post_id'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Post.php -- model

class Post extends Model
{
    protected $fillable = ['title','description','order'];

    public function postImage()
    {
        return $this->hasOne(PostImage::class);
    }
}

adjust the namespace for the models and migrations and you would be good to go... but you need some extra work to delete the image from storage and if save fails you could run the code for update inside a transaction. anyways good luck.

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen no post the original one before you implemented the job middleware... also your code worked before this refactor right? becuase right now you are not passing the language for the emails you wanna send

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen let me see the code for this job Verify($user, $language) you might not even need the middleware you might need on trait to use it in your jobs so it would set the locale for all your jobs... just post the code for the Verify job....

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen apologies on mobile device ... anyways you can shorten the code even more... try it now... btw make sure that your route middleware triggers the session condition first...

public function handle($job, $next)
{
        if (session()->has('lang')  &&  session('lang') === 'es') {
            $language = 'es'; 
        } else {
            $language = 'en';
        }

        $job->locale($language);

	$next($job);
}
Activity icon

Replied to Update Other Table With Relationships

@feelsonix let me see your migrations for post and image model i got 15mins i will send you the solution so you could just copy/paste and run it...

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen try this

public function handle($job, $next)
{
        if (request()->session()->has('lang')  &&  request()->session()->get('lang') === 'es') {
            $language = 'es'; 
        } else {
            $language = 'en';
        }

        $job->locale($language);

	$next($job);
}
Activity icon

Replied to Update Other Table With Relationships

@feelsonix just answer me this: in your scenario 1 post has many images right? post your models and controller here so if i get busy and won't be able to answer it on time some else might be able to help you. you might get a solution that way faster.

just start a new line with 3 ticks and paste your code then end it with three ticks

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen that's becuase you didn't implemented right... anyway go throught the docs and maybe find another examples but basically your middleware should look somthing like this.

public function handle($job, $next)
{
        if ($request->session()->has('lang')  &&  $request->session()->get('lang') === 'es') {
            $language = 'es'; 
        } else {
            $language = 'en';
        }

        $job->locale($language);

	$next($job);
}

so you check your session and set the job locale and then it gets the next job so on and forth....

Activity icon

Replied to Update Other Table With Relationships

@feelsonix i don't know what you are doing here, your model relationships are in contradiction with the code you have in your controller...

from your controller when you delete an image its gonna create problems for other posts base on the relationship you have defined there... so either your relations are wrong or the code in your controller...

so let me know what are you trying to accomplish here... then i might be able to help you...

Activity icon

Replied to Update Other Table With Relationships

@feelsonix is the relationaship between your Post and Image model 1-1 or 1-m ? and it would help if you could post your models here so we can help you better.

Activity icon

Replied to Laravel Realtime App

@laylowzk you can go with pure javascript but handling the browser side off thing with php!! that's a no no... so if its a small app you can use a minmal library like https://github.com/alpinejs/alpine or again pure vanilla js...

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen yes you can by using a job middleware https://laravel.com/docs/6.x/queues#job-middleware just like route middleware you can apply your conditions in the job middleware...etc

Activity icon

Replied to Laravel Realtime App

@laylowzk you can use https://docs.beyondco.de/laravel-websockets/ or firebase too many options depends on what you are trying to accomplish. but using a library might make your life easier...

Activity icon

Replied to Trying To Get Property 'name' Of Non-object

@munazzil seriously man look at$post->categories is a 1-m so i think your suggestion kinda blows....

Activity icon

Replied to Passing Locale To All Queued Mails?

@splendidkeen i don't get the whole picture but as far as i can understand it, you are dispatching a verification job which then sends an email based on the user's locale right? if so you can dispatch the job in the RedirectIfAuthenticated middleware which already ships with laravel. or in your Language middleware.

as i said i don't have the whole picture what you are trying to accomplish here... hope my answer gets you one step closer though...

Activity icon

Replied to Trying To Get Property 'name' Of Non-object

@monstajamss its probably because your $post->categories()->first() returns null or empty. just dump($post->categories->first())` and see if the relationship returns anything or not.

its better to just do $post->categories->first() and load the categories when you query post that way it would be faster and no extra unecessary queries... etc...

Apr
07
1 month ago
Activity icon

Commented on Guzzle API Requests With Tests

@bobbybouwmann hey man, how would you go about implementing what you did here with laravel 7's guzzle wrapper Http?

Dec
05
5 months ago
Activity icon

Replied to Custom Blade Directive For Date Format

@atef95 use the following and be sure to run php artisan optimize:clear after you edit the directive for the changes to take effect.

Blade::directive('formatDate', function ($date) {
    return "<?php echo ($date)->format('d-m-Y').'  '.($date)->timezone('Europe/Paris')->format('H:i:s'); ?>";
                });
~~
Activity icon

Replied to Old Value Is Not Show

@aronaman in order to use old value in select you have to use it in select options i'm on a mobile device so consider the following and apply it as you see fit:

@foreach($posts as $post)
    <option value={{$post->id}} {{$post->id == old('selectName')  ? "selected" : "" }}>{{$post->title}}</option>
@endforeach