mrkarma4ya

mrkarma4ya

Member Since 7 Months Ago

Experience Points
8,650
Total
Experience

1,350 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
59
Lessons
Completed
Best Reply Awards
1
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.

Level 2
8,650 XP
Feb
16
1 day ago
Activity icon

Replied to How Do I Check If The 'slug' Is Unique Across All Tables With 'slug' Column?

Edit:

Found the solution for error below: https://laracasts.com/discuss/channels/laravel/integrity-constraint-violation-1062?page=0

I created a migration for adding slug_id to posts table, but getting this error during migration:

Illuminate\Database\QueryException : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'posts_slug_id_unique' (SQL: alter table posts add unique posts_slug_id_unique(slug_id))

Migration:

public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            //
            $table->integer('slug_id')->unique();
        });
    }

For some reason, it looks like when migrating, its inserting '0' in all rows for slug_id, and getting error because its not unique. However, if I look at the table, the slug_id is already created with 0 in all rows, but the migration "failed".

I also tried switching from integer to string, same error but instead of Duplicate entry '0' its just Duplicate entry ''.

Activity icon

Replied to How Do I Check If The 'slug' Is Unique Across All Tables With 'slug' Column?

@sinnbeck Ok, one more question. Do I need to make the slug_id column in the posts table a foreign key that references the slugs table?

Activity icon

Replied to How Do I Check If The 'slug' Is Unique Across All Tables With 'slug' Column?

@sinnbeck

Uh, I don't think you understood me correctly. I want the slug to be unique across multiple tables, not non-unique on the same model.

Activity icon

Replied to How Do I Check If The 'slug' Is Unique Across All Tables With 'slug' Column?

@tray2

I don't really "need" to have it unique like that, but this is a personal project I'm doing to learn Laravel, and I'm trying to incorporate some complexity to learn better.

So as I understand, I need to create a slugs table with columns slug and slug_id.

The the posts, products and pages will also have a slug_id.

Then when creating a slug, I need to check if it exists in the slugs table, then update the table with the new slug, and put it's ID in the respective table (posts,pages,products).

Let me know if my understanding is correct.

Activity icon

Started a new Conversation How Do I Check If The 'slug' Is Unique Across All Tables With 'slug' Column?

Lets say I have a posts table, pages table and products table and they all have a slug column. Now when putting a new entry on either one of those, I want to check if the generated slug is unique across all the tables with the slug column. And if it already exists, I want to append a number (2,3,4, so on) automatically and check again.

For eg. if a post has slug hello-world and I make a page with a slug hello-world, it will be automatically changed to hello-world-2, and if if hello-world-2 also exists, it will be changed to hello-world-3 and so on.

This is my rough take:

$slugCheck = 0;
$slugAppend = 2;
while ($slugCheck = 0) 
{
    $slug = Str::slug($post->title,'-');
    $newSlug = $slug;
    if (...) //check if $newSlug already exists across multiple tables
    {
        $newSlug = $slug.'-'.$slugAppend;
        $slugAppend++;
    }
    else
    {
        $slugCheck = 1;
    }
}

$post->slug= $newSlug;
$post->save();

Please help me find a way to check if $newSlug already exists across multiple tables and refine the above code if possible.

Feb
15
2 days ago
Activity icon

Replied to How/where Do I Create Service Classes?

@sinnbeck So what's the laravel equivalent of "putting business logic in service classes"?

Activity icon

Replied to How/where Do I Create Service Classes?

@sergiu17 So is there an artisan command for it, or do I have to create it manually? Couldn't find it in the docs.

Feb
14
3 days ago
Activity icon

Replied to Calling Model Method From Controller

@sinnbeck Yea, I was writing my long reply while you gave the example.

@nakov Thanks for the good explanation, now I understand. Also, I had forgotten to use return in the method, now it's working!

Activity icon

Replied to Calling Model Method From Controller

@nakov

Okay, let me try to be clear.

Before I was doing this:

[email protected]:

public function index()
    {
        
        $categories = Category::orderBy('category', 'asc')->paginate(10);
        //return view('categories.index')->with('categories', $category);
    }

I read the above github article, which says:

Fat models, skinny controllers

Put all DB related logic into Eloquent models or into Repository classes if you're using Query Builder or raw SQL queries.

So, I'm trying to put this logic $categories = Category::orderBy('category', 'asc')->paginate(10); in my Category model like this:

Category.php:

class Category extends Model
{
    public function getAllCategories(){
        $this->orderBy('category', 'asc')->paginate(10);
    }
}

Now I'm trying to call the getAllCategories() method into my controller to get all the categories. But I have no idea how to do so.

Activity icon

Replied to Calling Model Method From Controller

That makes sense, but I am trying to make the DB queries from the model itself, not the controller.

Activity icon

Started a new Conversation Calling Model Method From Controller

Hello,

I'm trying to follow this: https://github.com/alexeymezenin/laravel-best-practices#fat-models-skinny-controllers

And I'm trying to exactly what they're doing, but getting an error.

Here's my model Category.php

class Category extends Model
{
    //
    public function posts(){
        return $this->belongstoMany('App\Post');
    }

    public function getAllCategories(){
        $this->orderBy('category', 'asc')->paginate(10)->get();
    }
}

Here's my [email protected]

public function index()
{      
   return view('categories.index', ['categories' => $this->category->getAllCategories()]);  
}

This is the error:

ErrorException Undefined property: App\Http\Controllers\CategoryController::$category

I'm not really sure how to properly call the method inside the model.

Feb
13
4 days ago
Activity icon

Replied to Prevent Scripts While Using {!! ... !!}

Huh, that's interesting. I guess I'll take a look at DomDocument then.

Activity icon

Replied to Prevent Scripts While Using {!! ... !!}

@fylzero @sinnbeck

Ok, so I added this function in my helpers file

if(!function_exists('htmlPurify')){
    function htmlPurify($string){
        $stripped = array("<script>","</script>");
        $replacement = array("","");
        return str_replace($stripped,$replacement,$string);
    }
}

And echoing like this:

 {!! htmlPurify($post->content) !!}

And it removed both <script> and </script> tags. Is there any other html tags I should strip in order to prevent malicious attacks?

Activity icon

Replied to Prevent Scripts While Using {!! ... !!}

@fylzero I want to allow all tags except <script> I guess, or any other ones that might be a security risk. So instead of allowing certain tags, I want to disallow certain tags.

@sinnbeck I'm having a hard time what that package does exactly. What do you mean by 'purify'?

Feb
12
5 days ago
Activity icon

Awarded Best Reply on Error Npm Run Production

I had the same issue last week, its something to do with Bootstrap files.

Here's the solution that worked for me (see the best answer in the following post):

https://laracasts.com/discuss/channels/elixir/npm-run-prod-fails-with-bootstrap?page=1

Activity icon

Replied to Error Npm Run Production

I had the same issue last week, its something to do with Bootstrap files.

Here's the solution that worked for me (see the best answer in the following post):

https://laracasts.com/discuss/channels/elixir/npm-run-prod-fails-with-bootstrap?page=1

Activity icon

Started a new Conversation Prevent Scripts While Using {!! ... !!}

Lets say I have a blog, and users can use HTML/CSS to style their posts. So, I would have to echo out the content like this to preserve the HTML/CSS right?

{!!$post->content!!}

But doing so, users are able to run <script> tags inside the input. How can I prevent that? What are the best security measures to take when doing something like this?

Activity icon

Started a new Conversation Take Form Value From Database, But Use Old Value If There's Error And Redirected.

Basically, I'm building a 'User Edit' page.

The form inputs will have the values from the database, eg

<input type="text" value"{{$user->name}}" placeholder="Your Name">

Now, when the user edits the name and submits the form, if there are any validation errors, s/he will be redirected back to the form with errors. Now I want the input field to have the data they previously entered, not from the database.

So, if they edit 'John Doe' to 'Jane Doe' and is redirected back with errors, the input field should say 'Jane Doe', not 'John Doe'.

How do I do this?

Activity icon

Awarded Best Reply on Image Intervention Not Doing Anything

Windows, Laragon.

Actually, I found the issue, turns out I had to manually save it.

Doing this worked:

$resizedAvatar = Image::make('storage/'.$avatar)->fit(600); //resize to 600x600
$resizedAvatar->save();
Activity icon

Replied to Image Intervention Not Doing Anything

Windows, Laragon.

Actually, I found the issue, turns out I had to manually save it.

Doing this worked:

$resizedAvatar = Image::make('storage/'.$avatar)->fit(600); //resize to 600x600
$resizedAvatar->save();
Activity icon

Started a new Conversation Image Intervention Not Doing Anything

I installed the intervention package, and I get no errors at all. But the image is unmodified. Here's my code:


use Intervention\Image\Facades\Image;

...

if ($request->hasFile('avatar')) {
            $avatar = ($this->generateImageFileName($request->file('avatar'), 'users'));
            $request->file('avatar')->storeAs('public', $avatar); //Upload Avatar
            //dd($avatar);
            Image::make('storage/'.$avatar)->fit(600); //resize to 600x600
            $user->avatar = $avatar; //Write to DB
        }

If I dump the Image::make line, I get this:

  #driver: Intervention\Image\Gd\Driver {#334 ▼
    +decoder: Intervention\Image\Gd\Decoder {#335 ▼
      -data: null
    }
    +encoder: Intervention\Image\Gd\Encoder {#336 ▼
      +result: null
      +image: null
      +format: null
      +quality: null
    }
  }
  #core: gd resource @509 ▼
    size: "600x600"
    trueColor: true
  }
  #backups: []
  +encoded: ""
  +mime: "image/png"
  +dirname: "storage/img/users"
  +basename: "BloodBorne-Dark-Souls-фэндомы-cleric-beast-5224478_95e0bfc9539c0ae8cbcf49017a14d9e5dc4db24e.png"
  +extension: "png"
  +filename: "BloodBorne-Dark-Souls-фэндомы-cleric-beast-5224478_95e0bfc9539c0ae8cbcf49017a14d9e5dc4db24e"
}

To install, I ran composer require intervention/image, added the service provider and facade alias as mentioned in the docs and ran composer install, just to be sure. Is there something I'm missing?

Feb
08
1 week ago
Activity icon

Started a new Conversation What's A Good Way To Learn User Roles And Permissions In Laravel?

I read that there are build in roles in Laravel, but can't find it in the documentation for 6.x

Should I try to learn it from scratch or use a package?

Also, what are some good resources for learning these?

Activity icon

Started a new Conversation What's A Good Way To Learn Parent/child Relationships In Laravel?

I want to create a 'Comment' feature in my website that allows replying to other people's comments and so on, and they are displayed in a 'nested' way. What's the best way to learn how to do it?

I found a tutorial here: https://serversideup.net/eloquent-parent-child-relationship-laravel/

But it was written in 2017, so things might have changed in newer Laravel versions. Is there a decent recent tutorial on this?

Feb
07
1 week ago
Activity icon

Replied to My App.js And App.css Are Not Being Minified By Laravel Mix

OK, thanks but I'm getting this error while running npm run prod

ERROR in ./resources/sass/app.scss (./node_modules/css-loader??ref--5-2!./node_modules/postcss-loader/src??postcss0!./node_modules/resolve-url-loader??ref--5-4!./node_modules/sass-loader/dist/cjs.js??ref--5-5!./resources/sass/app.scss)
Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError

(259:4) Unclosed block

  257 | 
  258 |   .navbar-toggler-icon {
> 259 |     background-image: escape-svg($navbar-light-toggler-icon-bg);
      |    ^
  260 |   }
  261 | 

Here's my app.scss file:

// Fonts
@import url('https://fonts.googleapis.com/css?family=Nunito');
// Variables
@import 'variables';
// Bootstrap
@import '~bootstrap/scss/bootstrap';
@import "variables.scss";
@import "mixins.scss";
@import "global.scss";
@import "navbar.scss";
@import "masthead.scss";
@import "post.scss";
@import "contact.scss";
@import "footer.scss";
@import "bootstrap-overrides.scss";
Activity icon

Started a new Conversation My App.js And App.css Are Not Being Minified By Laravel Mix

After doing an npm run dev on git-bash, the assets are bundled, but not minified. Why?

Activity icon

Replied to Getting The 'most_popular_tag'

Nice. Thanks!

Activity icon

Started a new Conversation Getting The 'most_popular_tag'

Lets say I have two models tag and post in a many-to-many relationship.

How do I retrieve the tag with the most highest number of associated posts?

Feb
06
1 week ago
Activity icon

Replied to Check If A Post Belongs In A Category

@sinnbeck

Yea, I called it category, maybe I'll change it later.

Anyway, your solution worked, just had to do this instead:

{{$post->category->firstWhere('id' , '1') ? 'Yes': 'No'}}

Thanks

Activity icon

Replied to Check If A Post Belongs In A Category

@fylzero @sinnbeck

None of those are working,

{{ ($post->category === 1) ? 'Yes' : 'No' }}
//Returns `No` even though post belongs to category with ID 1.
{{ ($post->category->id === 1) ? 'Yes' : 'No' }}
//Returns error `Property [id] does not exist on this collection instance.`

{{$post->category->firstWhere('id' , 1) ? 'Yes': 'No'}}
//also returns 'No'
Activity icon

Started a new Conversation Check If A Post Belongs In A Category

Post and Category are in a many-to-many relationship?

How do I check if the current post is in a category?

I'm trying this, but its not working:

{{$post->has(category,'1') ? 'Yes': 'No'}}
Feb
05
1 week ago
Activity icon

Started a new Conversation Comparing Wildcard Route

This is my code:

<li class="{{Request::path() === 'dashboard/posts' ? 'active' : ''}} ">

It adds an active class to the li tag if the current url is mywebsite.com/dashboard/posts

Now, I want to add the active class to all wildcard URLs with that structure, something like

<li class="{{Request::path() === 'dashboard/posts/*' ? 'active' : ''}} ">

so if the URL is something like mywebsite.com/dashboard/posts/edit, there's active class added.

Is it possible to achieve this?

Activity icon

Started a new Conversation Calling JS Function When Redirecting

How do you call a JS function after redirecting?

Let's say I redirected a form using return back() ->with('error','Form not submitted');

Now I want to alert this flashed data i.e. call alert('{{error}}'); on the redirected page.

How do I trigger the alert function?

Feb
02
2 weeks ago
Activity icon

Started a new Conversation What Would Be The Best Way To Insert Categories Into A Post?

Lets say I have 'Posts' and 'Categories' in a many-to-many relationship.

There's a pivot table with 'post_id' and 'category_id' columns.

When creating a new post with post_id = 1, the user is provided a list of all categories and they can select 0 or one or many categories. Lets say they select category with ID 1,3 and 5. So I just add the new rows to the pivot table like this: (post_id, category_id) -> [(1,1) , (1,3) , (1,5)].

Now lets say they edit the post and now they select some new categories and deselect some old ones. Lets say the new categories for the post are category_1, category_2, category_3 and category_4. Now, what would be the best way to make these changes?

My solution was to remove all rows from the pivot table where 'post_id' = 1. Then re-add the new rows in the table like this: (post_id, category_id) -> [(1,1) , (1,2) , (1,3) , (1,4)].

Is there a better way to achieve this?

Jan
27
3 weeks ago
Activity icon

Started a new Conversation Is There A Way To Enable A 'simple' Error Debug?

Currently, you have APP_DEBUG in .env file, which can be set to true or false, I believe.

Now, Laravel's debug is great, it gives a lot of info. Very useful during development.

But if I set to False, it doesn't give error at all, which is ok I guess.

But is there something in the middle of these two?

For eg. When I upload my app to a server and forget a database credential change, instead of showing everything like the current debugger does, or just giving a 500 | Server Error when I set it to false, I just want something like Cannot Establish Database Connection or something like that, just a simple error message.

Activity icon

Started a new Conversation Get Artisan Output When Running Artisan Commands From Php

I don't have access to SSH on my server, so I'm running some artisan commands from routes.

However, I don't know if they're executed successfully or not, and what errors prevented them from doing so.

For eg. here my web.php:

use \Illuminate\Support\Facades\Artisan;


Route::get('/migrate', function(){
    Artisan::call('migrate');
});

When I want to migrate, I know it didn't happen because the table that was supposed to be created wasn't created. But I can't see why.

Is there any way to display the output?

Jan
26
3 weeks ago
Activity icon

Replied to Form Not Submitting In Remote Server

@snapey

Holy F***, that's it!!!

Boss told me not to remove any old files on the public folder because SEO reasons, but I didn't even think something like this could happen! So, there was a booking folder there with some old files.

This explains a lot! That's why it was working in local but not in production!

Thanks for helping me everyone!!

Activity icon

Replied to Form Not Submitting In Remote Server

I am accessing the links directly by typing them, not by clicking on any links. So that's not the cause.

If I type thamel.com/booking, it automatically redirects to thamel.com/booking/ with a 301 redirect as seen on the network tab.

And I'm using /bookings just for testing purposes, I don't have a list of bookings to index. It's just to show that the problem is with the /booking route somehow, I will only have one of them if I solve this issue, probably /booking-form. I'm using the show method to just load the view from controller.

Activity icon

Replied to Form Not Submitting In Remote Server

@nakov

I don't have SSH access in the server, so I don't know how to run that and get output.

Secondly, I noticed something else.

I now have routes like this

Route::get('/booking', '[email protected]');
Route::get('/bookings', '[email protected]');

Both /booking and /bookings should do the same thing, right?

But looking at the URL and the network tab, /booking has a trailing slash, so the url is thamel.com/booking/ and /bookings, like everything else, does not. So the URL is thamel.com/bookings.

So, why did that trailing slash get added in /booking route? I read that the .htaccess is responsible for controlling that, but I haven't changed anything in there, its the same one shipped with Laravel.

Screenshot of comparision: https://i.imgur.com/OyrzYQU.png

Activity icon

Replied to Form Not Submitting In Remote Server

@nakov

Yea, but I just don't get why that error is caused in the first place!

I have no custom request, no user registration (except voyager stuff), nothing fancy at all.

In fact this is how the /booking page loads:

Here's the route:

Route::get('/booking', '[email protected]');

Here's the controller:

public function show(Booking $booking)
    {
        //
       
        return view('pages.booking');
    }

And I removed everything from booking.blade.php, its now just a hello world page

So why, when loading /booking link gives me a 403 error at the beginning of the network tab makes absolute no sense to me!

And on top of that, it works fine on the local setup!

EDIT: Here's a new development:

I changed the route to

Route::get('/bookings', '[email protected]');

And NO MORE 403 ERROR!

So is the route /booking reserved in Laravel in some way?? The only third party package I'm using is Voyager and I don't think that's whats causing it, since it works fine in local.

Or maybe /booking has some weird issue in my server? I checked the redirect and subdomains, nothing there. Nothing suspicious in .htaccess either.

Activity icon

Replied to Form Not Submitting In Remote Server

@nakov

APP_KEY is in my .env file.

I'm not making any AJAX requests.

I checked the network tab, just as I hit submit, the page refreshes and I can see a 403 error in the network tab, which should be 200 according to the working forms.

Here's a screenshot: https://imgur.com/a/Z6hbfkk

You can also visit the page directly if you want to see it.

I also cleared cloudflare cache, it didn't fix it.

Edit: the 403 is shown when loading the page itself too, not just when submitting.

Activity icon

Replied to Form Not Submitting In Remote Server

Yes the other form does work, and both forms work on the local server as well.

And the url is also fine, no public in the directory.

Activity icon

Started a new Conversation Form Not Submitting In Remote Server

I created a form that submits to a database, it works perfectly in local machine. But in the production server, it won't submit at all. It just 'reloads' the page, doesn't even hit the POST route at all.

Here's the form:

<form method="POST" action="/booking">
    @csrf
     .....
    <div class="form-group text-center" id="submit">
    <input type="submit" value="Get a Quote" name="submit" class="btn btn-success py-3 px-5">
    </div>
    <input type="hidden" name="recaptcha" id="recaptcha">
</form>

Route:

Route::get('/booking', '[email protected]');
Route::post('/booking', '[email protected]');

Controller:

public function store(Request $request)
    {
        //
        //Validation of input
        ddd('here');
        request()->validate([

When I click on submit button, the page just 'reloads', it doesn't hit the POST route.

It works in the local server, and another contact form with similar logic works as well.

Activity icon

Started a new Conversation URLS Are Absolute In Some Pages And Relative In Another

I'm using something like this for about page:

<a href="about">About</a>

This code is in my layout.blade.php file.

Now, normally, in my website, the above link is absolute. So if I'm on 'website.com/contact', the above url is 'website.com/about'. This is good, that's what I need.

But, I created another page using the same layout file, and the link is like this - 'website.com/booking/about' instead of just 'website.com/about'.

I even inspected the link in both pages, and both have <a href="about">About</a>, so I'm really confused why one is relative and another is absolute.

Also, this only happens in my remote server, the local website is working fine!

Activity icon

Replied to How To Update/merge Database On Production Database?

@ahmeddabak

Thanks. I have not changed any previous migration, just added a new migration for a new table.

Jan
25
3 weeks ago
Activity icon

Started a new Conversation How To Update/merge Database On Production Database?

I just added some more functionality to my project on local. There are some database structure updates too.

How can I upload them to my production server, without losing database entries on the server?

The migrations are present, so I guess running php artisan migrate on server would do it, but I don't know how to do that on server (no SSH access) (I tried running it from voyager compass, but got 500 internal server error).

Jan
20
4 weeks ago
Activity icon

Replied to [Concept] Laravel Docs Would Be Much Easier To Navigate With A Sticky Index Sidebar

@bugsysha Wow, that's really handy!

Still, a Laravel beginner wouldn't really know what to search for, so a sticky highlight links would come in handy.