Marinario

Software Engineer at ATIS

Member Since 1 Year Ago

Berat

Experience Points
4,440
Total
Experience

560 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
22
Lessons
Completed
Best Reply Awards
1
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.

  • Community Pillar

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

Level 1
4,440 XP
Jan
27
2 months ago
Activity icon

Replied to Decrement('column_name') On Trashed Related Model

Like I specified before dd($review->category) it gives me same results as dd($review->product):

Call to a member function withTrashed() on null

The problem is only when a related belongsTo is soft-deleted. I managed it in a very bad way but I had no choice at the moment and I don't have time right now to go and find a better solution.

Thanks for sharing larachat.slack.com with me.

Jan
22
2 months ago
Activity icon

Awarded Best Reply on Delete All Related Files On Folders From HasMany()?

Yes bro sure.

Here is how I manage it:

    public function forceDestroy(string $slug) :void
    {
        $product = Product::onlyTrashed()->findOrFail($slug);

        $productId = $product->id;

        $reviews = DB::select("SELECT * FROM reviews WHERE product_id = '$productId'");

        foreach ($reviews as $review) {

            $this->fileService->delete($review->invoice);

            $images = DB::select("SELECT * FROM images WHERE review_id = '$review->id'");

            foreach ($images as $image) {
                
                $this->fileService->delete($image->image_path);
            }

            DB::select("DELETE FROM images WHERE review_id = '$review->id'");

        }

        $this->fileService->delete($product->image);

        $product->reviews()->forceDelete();

        $product->forceDelete();
    }

I'm giving to you and everybody else the complete method so they can understand it better. You got delete() method posted already on question content.

I have used vanilla sql because I cannot use foreach for related hasMany() items on soft-deleted item and I don't know why.

Activity icon

Replied to Delete All Related Files On Folders From HasMany()?

and please not manipulating strings example... :P

Activity icon

Replied to Delete All Related Files On Folders From HasMany()?

Yes I know that, but I don't know any other way to manage it without observers.

Also I know about observer patterns but the docs have no example how to manage it.

So could you give me an example about handling any type of CRUD for related model or an example for forceDelete() in this case?

Activity icon

Replied to Delete All Related Files On Folders From HasMany()?

@michaloravec and see the thread here please where I've asked help about that problem:

https://laracasts.com/discuss/channels/eloquent/decrementcolumn-name-on-trashed-related-model

No one helped and I did not find any solution, so I decided to go the ugly way...

Activity icon

Replied to Delete All Related Files On Folders From HasMany()?

Show me an example. And the problem is that I cannot get the related hasMany() items for a soft-deleted item.

Can you give me an example of using observers and storage for my case?

Activity icon

Replied to Delete All Related Files On Folders From HasMany()?

Yes bro sure.

Here is how I manage it:

    public function forceDestroy(string $slug) :void
    {
        $product = Product::onlyTrashed()->findOrFail($slug);

        $productId = $product->id;

        $reviews = DB::select("SELECT * FROM reviews WHERE product_id = '$productId'");

        foreach ($reviews as $review) {

            $this->fileService->delete($review->invoice);

            $images = DB::select("SELECT * FROM images WHERE review_id = '$review->id'");

            foreach ($images as $image) {
                
                $this->fileService->delete($image->image_path);
            }

            DB::select("DELETE FROM images WHERE review_id = '$review->id'");

        }

        $this->fileService->delete($product->image);

        $product->reviews()->forceDelete();

        $product->forceDelete();
    }

I'm giving to you and everybody else the complete method so they can understand it better. You got delete() method posted already on question content.

I have used vanilla sql because I cannot use foreach for related hasMany() items on soft-deleted item and I don't know why.

Activity icon

Replied to Delete All Related Files On Folders From HasMany()?

Never mind figured out how to manage it.

Activity icon

Awarded Best Reply on How Can I Generate 10 Digit Unique Number That Will Be Sent To User After Registration On Laravel

Here, this is how I generate random 5 digit unique number for each user:

//Generating a random unique candidate_id for each applicant & adding 0 in upfront if id less than 5 digits
$candidatesData = Candidate::get(['candidate_id'])->toArray();
do {

$applicant_id = str_pad(rand(1, 5000), 5, "0", STR_PAD_LEFT);

} while (in_array($applicant_id, $candidatesData));

$candidate = Candidate::create($request->all());
$candidate->candidate_id = $applicant_id;
$candidate->save();

Please consider refactoring the code as per your needs.

Activity icon

Replied to How Can I Generate 10 Digit Unique Number That Will Be Sent To User After Registration On Laravel

Here, this is how I generate random 5 digit unique number for each user:

//Generating a random unique candidate_id for each applicant & adding 0 in upfront if id less than 5 digits
$candidatesData = Candidate::get(['candidate_id'])->toArray();
do {

$applicant_id = str_pad(rand(1, 5000), 5, "0", STR_PAD_LEFT);

} while (in_array($applicant_id, $candidatesData));

$candidate = Candidate::create($request->all());
$candidate->candidate_id = $applicant_id;
$candidate->save();

Please consider refactoring the code as per your needs.

Activity icon

Started a new Conversation Delete All Related Files On Folders From HasMany()?

I have products, reviews that are related to one product and images that are related to one review .

In case I delete the product, I want to delete product image and all related images for each review from the folders.

The images of each reviews are grouped in one table named images and there is where I save the path for each image.

I have declared all the relations on the model and everything works fine.

The problem is when I try to delete the related images for each review. There is no error but just the images are not being deleted.

This is how I'm trying to delete all image files related to each review.

 $product = Product::onlyTrashed()->findOrFail($slug);

//Here I delete successfully the product image.
$this->fileService->delete($product->image);

//Here I'm trying to delete the related images for each review
foreach ($product->reviews as $review) {

            foreach ($review->images as $image) {
                
                $this->fileService->delete($image->image_path);
            }
}

this->fileService->delete() is just a service which looks like this:

public function delete($property)
{
    return \File::delete(storage_path('app/public/'.$property));
}

Is there any other way to achieve this, and how can I improve my code to successfully delete related images for each review from the folder?

Jan
21
2 months ago
Activity icon

Replied to Image Intervention: Can't Write Image Data To Path

I'm sure someone in future will need to use image intervention with storage file and will struggle until the correct solution so I'm sharing the code:

public function saveImage(string $path, $image)
{
    $file = $image;

    $filename = Str::random(20) . $file->getClientOriginalName();

    $imgResize = Image::make($image->getRealPath())->heighten(300);

    $imgResize->stream();

    return $destination_path = Storage::disk('local')->put('/'.$path.'/'.$filename, $imgResize);
}

Happy coding!

Activity icon

Replied to Image Intervention: Can't Write Image Data To Path

Yes it works, thank you! I had to add the $filename also.

Activity icon

Awarded Best Reply on Image Intervention: Can't Write Image Data To Path

Ok I got it:

$imgResize->save(storage_path('app/public/'.$path.'/'.$filename));

I had to add the $filename too.

Thanks to anyone and shame on me :P

P.S. I got the answer from my question on stackoverflow: https://stackoverflow.com/questions/65825518/laravel-8-image-intervention-cant-write-image-data-to-path?noredirect=1#comment116384307_65825518

Activity icon

Replied to Image Intervention: Can't Write Image Data To Path

Ok I got it:

$imgResize->save(storage_path('app/public/'.$path.'/'.$filename));

I had to add the $filename too.

Thanks to anyone and shame on me :P

P.S. I got the answer from my question on stackoverflow: https://stackoverflow.com/questions/65825518/laravel-8-image-intervention-cant-write-image-data-to-path?noredirect=1#comment116384307_65825518

Activity icon

Replied to Image Intervention: Can't Write Image Data To Path

The value is just the folder name where I'm trying to save it.

Activity icon

Replied to Image Intervention: Can't Write Image Data To Path

If I try to save it to somewhere else like : $imgResize->save(storage_path('app/public/'.$filename)); it works.

If I try to save it to $path it will throw the same error again.

The problem is that I'm using this method inside a service which works for many other services/controllers and I get the $path dynamically so I cannot do this: $imgResize->save(storage_path('app/public/folder_name'));

Activity icon

Replied to Image Intervention: Can't Write Image Data To Path

Hey @aurawindsurfing yes I did earlier php artisan storage:link and that's why it works without using image intervention.

I did dd(storage_path('app/public/'.$path)); which results in the same folder in which the normal images are saved successfully.

I also checked if is_writable and the result is true.

Just for testing purposes I already changed the permissions to 777.

I don't know what else to do to make this work.

Activity icon

Started a new Conversation Image Intervention: Can't Write Image Data To Path

This is how I'm trying to use image intervention package:

public function saveImage(string $path, $image)
    {
            $file = $image;
            $filename = Str::random(20) . $file->getClientOriginalName();

            $imgResize = Image::make($image);
            $imgResize->heighten(300);

            //dd(is_writable(storage_path('app/public/'.$path)));

            $imgResize->save(storage_path('app/public/'.$path));


            return $destination_path = Storage::disk('local')->put('/'.$path, $image);    
    }

The image is saved successfully without using image intervention. When I try to save() it it will throw me this error:

Intervention\Image\Exception\NotWritableException: Can't write image data to path.

I have already changed the permissions of the folder, but still not working.

Any idea what is causing this?

Jan
18
2 months ago
Activity icon

Awarded Best Reply on Decrement('column_name') On Trashed Related Model

It's impossible & disappointing that no one could give me even an ugly solution to my problem. Anyway I'm sharing my solution because in the future someone will need it and I don't want anyone to struggle.

My ugly solution consists on doing it all this in vanilla sql:

public function deletePermanentlyService(int $id) :void
    {
        $review = Review::onlyTrashed()->findOrFail($id); 

        $productId = $review->product_id;

        $categoryId = $review->category_id;

        DB::select("update categories set total_reviews = total_reviews-1 where id = '$categoryId'");

        DB::select("update products set total_reviews = total_reviews-1 where id = '$productId'");

        if ($review->no_yes == 'yes') {

            DB::select("update categories set total_yes = total_yes-1 where id = '$categoryId'");
            
            DB::select("update products set total_yes = total_yes-1 where id = '$productId'");

        } elseif ($review->no_yes == 'no') {

            DB::select("update categories set total_no = total_no-1 where id = '$categoryId'");

            DB::select("update products set total_no = total_no-1 where id = '$productId'");
        }

        $review->forceDelete();

    }

I hope this will help someone in the future and that laravel could give more options on working with soft-deleted models...

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

It's impossible & disappointing that no one could give me even an ugly solution to my problem. Anyway I'm sharing my solution because in the future someone will need it and I don't want anyone to struggle.

My ugly solution consists on doing it all this in vanilla sql:

public function deletePermanentlyService(int $id) :void
    {
        $review = Review::onlyTrashed()->findOrFail($id); 

        $productId = $review->product_id;

        $categoryId = $review->category_id;

        DB::select("update categories set total_reviews = total_reviews-1 where id = '$categoryId'");

        DB::select("update products set total_reviews = total_reviews-1 where id = '$productId'");

        if ($review->no_yes == 'yes') {

            DB::select("update categories set total_yes = total_yes-1 where id = '$categoryId'");
            
            DB::select("update products set total_yes = total_yes-1 where id = '$productId'");

        } elseif ($review->no_yes == 'no') {

            DB::select("update categories set total_no = total_no-1 where id = '$categoryId'");

            DB::select("update products set total_no = total_no-1 where id = '$productId'");
        }

        $review->forceDelete();

    }

I hope this will help someone in the future and that laravel could give more options on working with soft-deleted models...

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

I also tried to do this using Query Builder but the error this time says:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

This is how I tried:

DB::table('products')->decrement('total_reviews', 1, ['id' => $review->product_id]);

And then I try to delete: $review->forceDelete();. The problem is on decrement a field on soft-deleted product.

What I don't understand is why I can't update a soft-deleted. Is there any way to update a soft-deleted or not?

Jan
15
2 months ago
Activity icon

Replied to Decrement('column_name') On Trashed Related Model

Yes I know, in this case the product is soft-deleted and still is not working. I tried with withTrashed also but same error as was with onlyTrashed.

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

The bindings should be the product_id from the Review? : Yes.

I've tried dd(Product::onlyTrashed()->findOrFail($review->product_id)); also but the error:

No query results for model [App\Models\Product]

So I cannot even catch the product using the $review->product_id.

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

If I do:

dd($review->product());

It will show me:

Illuminate\Database\Eloquent\Relations\BelongsTo {#454 ▼
  #child: App\Models\Review {#1526 ▶}
  #foreignKey: "product_id"
  #ownerKey: "id"
  #relationName: "product"
  #query: Illuminate\Database\Eloquent\Builder {#560 ▶}
  #parent: App\Models\Review {#1526 ▶}
  #related: App\Models\Product {#1439 ▶}
  #withDefault: null
}

If I try to dd($review->product); it will throw the same error.

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

Yes that's right. Now that I'm thinking maybe the issue will be for the category too in case that the related category would be soft-deleted to...

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

Yes of course.

Product model:

public function reviews()
   {
       return $this->hasMany(Review::class, 'product_id', 'id');
   }

Review model:

public function product()
    {
        return $this->belongsTo(Product::class);
    }

reviews migrations:

public function up()
    {
        Schema::create('reviews', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('status_id');
            $table->unsignedBigInteger('product_id')->nullable();
            $table->unsignedBigInteger('content_id')->nullable();
            $table->string('title')->nullable();
            $table->text('other_content')->nullable();
            $table->string('no_yes');
            $table->string('shop_name');
            $table->string('shop_address');
            $table->string('invoice')->nullable();
            $table->string('product_origin')->nullable();
            $table->string('declined_reason')->nullable();
            $table->string('approved_by')->nullable();
            $table->softDeletes();
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('category_id')->references('id')->on('categories');
            $table->foreign('status_id')->references('id')->on('statuses');
            $table->foreign('product_id')->references('id')->on('products');
            $table->foreign('content_id')->references('id')->on('contents');
        });
    }
Activity icon

Replied to Decrement('column_name') On Trashed Related Model

Still same error... strange

Edit: Sorry no same error but:

Call to a member function withTrashed() on null
Activity icon

Replied to Decrement('column_name') On Trashed Related Model

I don't really understand why, yes it throws me that error but the review itself with the last method is deleted, the category is decremented, but the product which is softdeleted is not decremented.

I may think that the category has nothing to do with that...

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

I've tried also this:

public function deletePermanentlyService(int $id) :void
    {
        $review = Review::onlyTrashed()->findOrFail($id);

        $review->forceDelete();

        if ($review->no_yes == 'yes') {

            $review->category->decrement('total_reviews');
            $review->category->decrement('total_yes');

            $product = $review->product;
            $product->decrement('total_reviews');
            $product->decrement('total_yes');

        } elseif ($review->no_yes == 'no') {

            $review->category->decrement('total_reviews');
            $review->category->decrement('total_no');

            $product = $review->product;
            $product->decrement('total_reviews');
            $product->decrement('total_no);
        }

    }

Still shows me

Call to a member function decrement() on null
Activity icon

Replied to Decrement('column_name') On Trashed Related Model

And I'm doing this test following the workflow, so softdelete the product and related review and then forcedelete the review one by one.

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

No the category is not softdeleted. The category is ok. The error is showed on the line in which I try to decrement the product.

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

So the idea is that first i try to soft delete the product which soft deletes reviews also. After doing this I try to forcedelete the review decrementing from category and product which for the trashed product results in that error.

Activity icon

Replied to Decrement('column_name') On Trashed Related Model

let me give all the method so you can undertstand better my situation:

public function deletePermanentlyService(int $id) :void
    {
        $review = Review::onlyTrashed()->findOrFail($id);

        if ($review->no_yes == 'yes') {

            $review->category->decrement('total_reviews');
            $review->category->decrement('total_yes');

            $review->product->decrement('total_reviews');
            $review->product->decrement('total_yes');

        } elseif ($review->no_yes == 'no') {

            $review->category->decrement('total_reviews');
            $review->category->decrement('total_no');

            $review->product->decrement('total_reviews');
            $review->product->decrement('total_no');
        }

        $review->forceDelete();

    }
Activity icon

Started a new Conversation Decrement('column_name') On Trashed Related Model

I'm trying to decrement like this on related hasOne trashed item but it throws me an error.

$review->category->decrement('total_reviews');

The error:

Call to a member function decrement() on null

Can I decrement on related model which is trashed, and how can I achieve that?

P.S. I tried doing it manually with -- operator decrementing with 1 but throws this error:

Indirect modification of overloaded property App\Models\Review::$category has no effect...

Thanks

Jan
13
2 months ago
Activity icon

Replied to Redirect Back To Same Page After Changing Locale

It will work for all array $langs elements but for it' language will not work.

        $thisUrl = url()->current().'/';
        $appLocale = app()->getLocale();


        //Lets Say You Have Array of Languages
        $langs = [
            'en' => ['label' => 'English','url' => ''],
            'it' => ['label' => 'Italian','url' => ''],
            'de' => ['label' => 'German','url' => '']
        ];

        //Remove the current Language Url
        unset($langs[$appLocale]);
        //Generating Urls For All of Your Languages
        foreach ($langs as $lang => $labels) {
            $langs[$lang]['url'] = str_replace('/' . $appLocale . '/', '/' . $lang . '/', $thisUrl);
        }

        View::share('langs', $langs);

Blade:

         @foreach($langs as $code => $labels)
          <a class="dropdown-item" href="{{ $labels['url'] }}">
              <span class="lang lang-{{ $code }}">{{ $labels['label'] }}</span>
          </a>
          @endforeach

It will show en and de but not it. Strange...

I want to specify that my default and fallback_locale are it.

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

@khaledw62 and I have to specify that if I use the blade solution will work just fine. If I use AppServiceProvider solution will give me this problem so the locale will be changed only from it to en but not the other way around.

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

Thanks again @khaledw62.

Look I was testing and in first place all seems good but there is a problem with AppServiceProvider solution and I can't understand why.

$thisUrl = url()->current().'/';
        if (app()->getlocale() == 'en') {
            $newUrl  = str_replace('/en/', '/it/', $thisUrl);
        } else {
            $newUrl  = str_replace('/it/', '/en/', $thisUrl);
       }

View::share('newUrl', $newUrl);

When I change first from /it/ to /en/ there are no problems. But when I try to change it from actual /en/ to /it/ it will redirect back to same page but with no locale changed. I've tested with dd the $newUrl variable and the print is correct and the locale is changed every time I change it. But it is not working on <a> tag.

This is how my blade looks like:

<div class="dropdown-menu" aria-labelledby="languageDropdown">
          @if ( Config::get('app.locale') == 'it')
          <a class="dropdown-item" href="{{ $newUrl }}">
            <span class="lang lang-en">English</span>
          </a>
          @elseif ( Config::get('app.locale') == 'en' )
          <a class="dropdown-item" href="{{ $newUrl }}">
            <span class="lang lang-it">Italian</span>
          </a>
          @endif
</div>

Maybe I'm doing something wrong in blade but my mind is really blocked now.

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

Thanks for the suggestion @michaloravec , I know about mcamara package but the problem is that I have already completed the project and that was the last bug to fix. And I don't know how it will affect the project starting over with localization using mcamara package...

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

@khaledw62 I have another question related to my question even that the problem is already solved.

In case that in future I add other language like de and others languages as well, how can I manage it in that case.

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

No in fact, your title gave me the example... I saw it at your post and the credentials for that goes to you... Thanks again and Happy Coding!

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

Yes @sr57 you're right I forgot it. Thanks!

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

Brother thank you very much because that worked for me. That is a very simple and good solution to my problem. May God bless you!

I'm sure that many will benefit from your answer about redirecting back with locale because in 3 days no one could give me correct answer in several forums.

Again, thank you!

Activity icon

Replied to Redirect Back To Same Page After Changing Locale

Sorry for the late response @khaledw62 but once we get off the office we cannot access remotely our projects from home.

Let me give a try and I will tell you.

Jan
12
3 months ago
Activity icon

Replied to Redirect Back To Same Page After Changing Locale

I tried achieving that using Route:: helper but the problem is on the pages that have parameters.

<a class="dropdown-item" href="{{ route(Route::currentRouteName(), 'en') }}">

But it throws this error:

Missing required parameters for [Route: frontend.category] [URI: {locale}/{slug}]. (View: /var/www/html/project/resources/views/frontend/layouts/header.blade.php).

I cannot put parameters since the language switcher is on header and the parameters are different and many...

Any help would be appreciated!

Jan
11
3 months ago
Activity icon

Started a new Conversation Redirect Back To Same Page After Changing Locale

The way I implemented multilang is through middleware and routes.

Middleware Localization.php looks like this:

    public function handle(Request $request, Closure $next)
    {
        $locale = $request->segment(1); 


        if(empty($locale)) { 
            return redirect()->to('/' . app()->getLocale());
        }

        if(in_array($locale, ['en','it'])) {
            App::setLocale($locale);
            $request->except(0); 
        }

        return $next($request);
    }

And in my web.php I have:

Route::get('locale/{locale}', function ($locale){
    \Session::put('locale', $locale);
    $path = Route::getCurrentRoute()->getPath();

    return redirect($path);
})->name('langroute');

In blade I'm using it like this:

<a class="dropdown-item" href="{{ url('/en') }}">

How can I redirect back to same page after changing to another lang?

Jan
08
3 months ago
Activity icon

Replied to Getting All Data From Pivot Table Using Foreach On Blade.

Yeah sorry, anyway I did not get it why I need to eager load with 1 user...

Activity icon

Replied to Getting All Data From Pivot Table Using Foreach On Blade.

That is strange because without Eager loading (with()) does not work...

That's why I was struggling because I had only 1 user and I thought that I did not needed Eager loading. Anyway strange day today. Maybe bcs its friday :P

Activity icon

Replied to Getting All Data From Pivot Table Using Foreach On Blade.

I had only to change the way catching user in controller. So i needed eager loading as @tray2 specified:

$user = User::with('shareables')->findOrFail($slug);

And in blade the classic @foreach:

@foreach($user->shareables as $shareable)
	{{ $shareable->name }}
@endforeach

Thanks again @tray2.