Creating and Viewing a Subweddit

 To begin making a subweddit, we must make 4 things - 

  • A Subweddit model
  • A make_subweddit_table migration
  • A Subweddit factory (a useful laravel technique for filling a database table with fake data
  • A subweddit Controller, to control the data

All 3 can be made by the command:

php artisan make:model Subweddit -fmc

(the suffix -fmc does the magic, making the factory, migration and controller)

For the miagration - this is the layout as it stands:


Apart from the ordinary id and timestamps, the subweddit table contains the subweddit name, bio and mod_id, which, by default, is the user who created the subweddit, they will be able to delete the subweddit, and in the future remove posts as well as comments from posts. 


Now we are able to fill in the factory to create some fake data.

after altering SubwedditFactory.php to look like so



and attempting to use the factory by running 

factory(App\Models\Subweddit)->create(); 

I encountered a problem 




PHP Fatal error: Undefined constant App\Models\Subweddit in Psy Shell code on line 1


This was due to laravel 8 using a different way of defining, and calling factories.

After updating the factory file to look like so:



and calling:

App\Models\Subweddit::factory()->create();

we got our first results!



We can now update our routes so that visiting '/w/{subweddit}', will call the SubwedditController 'show' which simply returns a view, passing in the data from the given subweddit



Now, instead of using a factory, lets try create our own subweddit using a form. I started by adapting my routes file to include 'w/create' and adding a method 'create' to the controller to return a page showing a form to create a subweddit.


As you can see, this sends a post request to '/w/', which calls the 'store' method in the Subweddit Controller which creates an instance of the subweddit object and binds the given attributes from the post request to the according database columns.



A nifty trick is to import Illuminate/Support/Facades/Auth, this way we can retrieve the authenticated user by
calling Auth::id. In this case, we are setting the authenticated user as the subweddit mod.

We now have subweddits!

·

Comments

Popular posts from this blog

Final Database Design

Views and Policies

Validation