moshemo

moshemo

Member Since 3 Years Ago

Experience Points
16,630
Total
Experience

3,370 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
158
Lessons
Completed
Best Reply Awards
0
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 4
16,630 XP
Mar
31
2 days ago
Activity icon

Replied to Error When Using A Factory For A Foreign Key

That question did it -- I had to change the order of my DatabaseSeeder.php file. I was calling the CategoryNewsTableSeeder before I called the NewsSeederTable.

Thanks.

Activity icon

Started a new Conversation Error When Using A Factory For A Foreign Key

I have the following migration (for a pivot table):

        Schema::create('category_news', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('news_id');

            $table->unique(['category_id', 'news_id']);

            $table->foreign('news_id')->references('id')->on('news')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });

I want to seed that table with some dummy data -- to do so, I have created the following factory:

$factory->define(CategoryNews::class, function (Faker $faker) {

  return [
    'category_id' => $faker->numberBetween($min = 1, $max = 35),
    'news_id' => $faker->numberBetween($min = 1, $max = 150)
  ];

});

However, when I run the following command: php artisan migrate:fresh --seed, I get the following error:

 Illuminate\Database\QueryException

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE) (SQL: insert into `category_news` (`category_id`, `news_id`, `updated_at`, `created_at`) values (16, 13, 2020-03-31 10:44:04, 2020-03-31 10:44:04))

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673|

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE)")

  2   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOStatement::execute()

Any idea why and what I need to do to fix it?

Thanks.

Mar
30
3 days ago
Activity icon

Replied to Factory & Seeder For Pivot Table

@andonovn

I tried this -- this is the error I received:

  Class 'category_news' not found

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:232
    228|         if ($this->amount < 1) {
    229|             return (new $this->class)->newCollection();
    230|         }
    231|
  > 232|         $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
    233|             return $this->makeInstance($attributes);
    234|         }, range(1, $this->amount)));
    235|
    236|         $this->callAfterMaking($instances);

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:169
      Illuminate\Database\Eloquent\FactoryBuilder::make([])

  2   C:\laragon\www\startup-reporter\database\seeds\CategoriesNewsTableSeeder.php:14
      Illuminate\Database\Eloquent\FactoryBuilder::create()
Activity icon

Started a new Conversation Factory & Seeder For Pivot Table

I am trying to create a factory and seeder for a pivot table. I am trying to do so without creating a model just for the pivot table. However, in doing so, I am getting an error. Before I show the error, here are my files:

// CategoryNewsFactory.php
use App\Model;
use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    DB::table('category_news')->insert(
      [
          'category_id' => factory(App\Category::class)->create()->id,
          'news_id' => factory(App\News::class)->create()->id,
      ]
  );
});
// CategoriesNewsSeeder.php

    public function run()
    {
        factory(App\Model::class, 35)->create();
    }

And here is my error message:

   Error

  Class 'App\Model' not found

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:232
    228|         if ($this->amount < 1) {
    229|             return (new $this->class)->newCollection();
    230|         }
    231|
  > 232|         $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
    233|             return $this->makeInstance($attributes);
    234|         }, range(1, $this->amount)));
    235|
    236|         $this->callAfterMaking($instances);

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:169
      Illuminate\Database\Eloquent\FactoryBuilder::make([])

  2   C:\laragon\www\startup-reporter\database\seeds\CategoriesNewsTableSeeder.php:14
      Illuminate\Database\Eloquent\FactoryBuilder::create()

So I am wondering, what am I doing wrong and how can I fix it?

Thanks.

Mar
26
1 week ago
Activity icon

Started a new Conversation Migration & Seeding Problems

I am trying to seed a database and am getting an error when I run php artisant migrate and a different error when I run php artisan migrate:fresh.

Here are the errors.

php artisan migrate:


   Illuminate\Database\QueryException

  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'news' already exists (SQL: create table `news` (`id` bigint unsigned not null auto_increment primary key, `created_at` timestamp null, `updated_at` timestamp null, `title` varchar(255) not null, `slug` varchar(255) null, `article_url` varchar(255) null, `category` varchar(255) null, `img_url` varchar(255) null, `keywords` varchar(255) null, `source` varchar(255) null, `date_published` date null, `excerpt` text null, `body` text null, `author_id` bigint unsigned not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673|

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOException::("SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'news' already exists")

  2   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOStatement::execute()

And here is the php artisan migrate:fresh error:

 Illuminate\Database\QueryException

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `news` add constraint `news_author_id_foreign` foreign key (`author_id`) references `authors` (`id`) on delete cascade)

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673|

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

  2   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOStatement::execute()

Here are the migration files:

Schema::create('news', function (Blueprint $table) {
  $table->bigIncrements('id');
   ...
  $table->unsignedBigInteger('author_id');
  $table->foreign('author_id')
    ->references('id')
    ->on('authors')
    ->onDelete('cascade');
});
Schema::create('authors', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});

And here are the factory files:

$factory->define(Author::class, function (Faker $faker) {
    return [
        'name' => $faker->name
    ];
});
    return [
      ...
      'author_id' => $faker->numberBetween($min = 1, $max = 50),
    ];

And finally, here are the seed files:

// DatabaseSeeder
    {
        $this->call(AuthorsTableSeeder::class);
        $this->call(NewsTableSeeder::class);
    }

// NewsSeeder and AuthorSeeder

factory(App\News::class, 150)->create();
factory(App\Authors::class, 50)->create();

Any idea why I am getting these errors and what I can do to fix them?

Thanks.

Activity icon

Started a new Conversation Automatically Create Slug From Title Using Create & Validate Methods

I want to automatically create a slug and save it to the database based on the title entered into a form. Currently, this is how my controller is set up:

  public function store(News $id) {
    News::create($this->validateArticle());
    return redirect('/news');
  }

  public function validateArticle() {
    return request()->validate([
      'title' => 'required',
      'excerpt' => 'nullable',
      'body' => 'nullable'
    ]);
  }

How can I modify this code so that I automatically generate a slug based off of the title?

Thanks.

Activity icon

Replied to Accessing Path Function In Model In Index File

That was the problem. I hadn't run artisan factory yet. Thanks.

Activity icon

Started a new Conversation Accessing Path Function In Model In Index File

I have set up the following function in my model:

  public function path() {
    return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
  }

I would now like to access that function in my index.blade.php file -- like this:

  @foreach ($articles as $article)
  <a href="{{ $article->path() }}">
	// rest of code goes here
  </a>
  @endforeach

But when I try this, I get the following error:

Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: news.show] [URI: news/{id}/{slug}]. (View: C:\laragon\www\startup-reporter\resources\views\news\index.blade.php)

Here is what my routes (web.php) looks like:

Route::get('news', '[email protected]')->name('news.index');
Route::get('news/create', '[email protected]')->name('news.create');
Route::get('news/{id}/{slug}', '[email protected]')->name('news.show');
Route::get('news/{id}/edit', '[email protected]')->name('news.edit');

Route::post('news', '[email protected]')->name('news.store');
Route::put('news/{id}', '[email protected]');

And here is my controller:

  // Index
  public function index() {
    $news = News::latest()->get();
    return view('news.index', ['articles' => $news]);
  }

  // Show
  public function show(News $id) {
    return view('news.show', compact('id'));
  }

Any idea why this is not working and what I need to do to get this to work?

Thanks.

Mar
25
1 week ago
Activity icon

Replied to Path Function For URL With ID And Slug

I tried that, but I still get an error when testing it out in tinker. Here is my web.php file looks like:

Route::get('articles/{article}/{slug}', '[email protected]')->name('articles.show');

And here is my path function:

public function path() {
    return route('articles.show', $this);
  }

I then fire up tinker and run that path function and get the following error:

Illuminate/Routing/Exceptions/UrlGenerationException with message 'Missing required parameters for [Route: articles.show] [URI: articles/{article}/{slug}].'

Any idea why?

Activity icon

Started a new Conversation Path Function For URL With ID And Slug

I am referencing this episode: https://laracasts.com/series/laravel-6-from-scratch/episodes/28?autoplay=true

In that episode, Jeffrey creates the following function in the Article model:

  public function path() {
    return route('article.show', $this);
  }

Now, this works just fine and returns the following url structure: www.mydomain.com/article/{id}

However, I would like to tweak it a bit. I want my url structure to be like this: www.mydomain.com/article/{id}/{slug}

So, what I want to know is how do I have to modify the path function in order to return this url structure - i.e., the one with both the id and the slug?

Activity icon

Replied to Create Method With Validating Only Some Fields

Thanks - that's exactly what I needed to know. Much appreciated.

Activity icon

Started a new Conversation Create Method With Validating Only Some Fields

I am referencing this episode: https://laracasts.com/series/laravel-6-from-scratch/episodes/27

Jeffrey notes a way to use the create with the validate method -- like this:

Article::create(request()->validate([
 'title' => 'required',
 'excerpt' => 'required',
 'body' => 'required'
]));

My question is how could I rework this code if I only wanted to validate some of the fields (so, only the title field). How could I do that?

Thanks.

Mar
11
3 weeks ago
Activity icon

Started a new Conversation How To Handle Multiple (Post)CSS Files With Laravel Mix

I have a main stylesheet (styles.css) and a css library that I downloaded (hamburgers.css from https://github.com/jonsuh/hamburgers).

I have already set up Laravel Mix to process my styles.css file using mix.postCss (while passing in a few postCss plugins such as purgeCss). I now want to ALSO concatenate my styles.css and the hamburgers.css file together into one production ready css file (using purgeCss to remove unused css in BOTH my styles.css file and the hamburgers.css file).

However, I am having trouble figuring out how to best do this. I know that I can concatenate plain css files together using mix.styles. And I know that I can process postCss using mix.postCss.

But how can I BOTH concatenate and process?

For now, what I am doing is importing hamburgers.css into styles.css (which then gets processed using mix.postCss). I am wondering though if a) there is a reason NOT to do it that way and b) a BETTER way to do it.

Any ideas?

Thanks.