#laravel faker factory
Explore tagged Tumblr posts
owthub · 2 years ago
Text
Step-by-Step Complete Laravel Video Tutorials
Laravel is a well-known open-source PHP web application framework that is well-known for its elegant syntax, developer-friendly features, and solid ecosystem. It simplifies and speeds up web application development, making it an excellent solution for a wide range of online projects, from simple websites to sophisticated business apps.
0 notes
laravelvuejs · 6 years ago
Text
How to make a Laravel API - Tutorial 2, Seeding fake data with a factory - Laravel
How to make a Laravel API – Tutorial 2, Seeding fake data with a factory – Laravel
How to make a Laravel API – Tutorial 2, Seeding fake data with a factory – Laravel
[ad_1]
This tutorial will use Laravel’s factories and faker to seed entries into the database.
Get the code here: https://github.com/QuentinWatt/how-to-make-an-api-with-laravel
Follow me on social media: Twitter: @QuentinWatt Facebook: @quentinwatt Instagram: @quentinwatt
Subscribe: https://www.youtube.com/c/QuentinW…
View On WordPress
1 note · View note
codesolutionsstuff · 3 years ago
Text
How To Use Chart JS In Laravel 
Tumblr media
The fundamentals of Chart.js are quite straightforward. First, we must install Chart.js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. Simply connecting to the created CDN version in the sample's blade file would suffice for this brief example. A The fundamentals of Chart js are quite straightforward. First, we must install Chart js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. In our examples, we'll only link to the built-in CDN version for the purposes of this brief demonstration. We'll just plot the ages of the app users in this case. We're presuming you've already set up the Laravel auth scaffolding and carried out the required migrations to make a Users table. If not, take a look at the information here or modify it for the model you're using for your chart's data. Therefore, before creating any users at random, we'll first add an age column to our Users table. For more information, see our post on how to use faker to create random users, however for this demonstration, let's make a database migration to add an age column by using: add age to users table php artisan make:migration —table='users' To change the up function to: edit this file in the database migrations directory. Schema::table('Users', function (Blueprint $table) { $table->int('age')->nullable(); }); Run php artisan migrate after that, and your Users table should now contain an age column. Visit /database/factories/UserFactory now, and add the following at the end of the array: 'age' is represented by $faker->numberBetween($min = 20, $max = 80), The complete return is thus: return ; Run the following commands to build a UsersTableSeeder: make:seeder UsersTableSeeder in PHP This will produce UsersTableSeeder.php in the database. The run function should include the following: factory(AppUser::class, 5)->create(); When this is executed, 5 users will be created; modify 5 to the number of users you need. After that, we must open DatabaseSeeder.php in /database/seeds and uncomment the code in the run() function. Finally, execute php artisan db:seed. Five new users should appear, each of whom has an age. For our Charts page, we will now develop a model, controller, views, and routes. Run the following command in PHP: make:controller ChartController —model=Chart. To the file /app/Http/Controllers/ChartController.php, add the following: use AppUser; use AppChart; use DB; ... public function index() { // Get users grouped by age $groups = DB::table('users') ->select('age', DB::raw('count(*) as total')) ->groupBy('age') ->pluck('total', 'age')->all(); // Generate random colours for the groups for ($i=0; $ilabels = (array_keys($groups)); $chart->dataset = (array_values($groups)); $chart->colours = $colours; return view('charts.index', compact('chart')); } The random colour scheme is one example of the exciting things you can do with the controller's data, though you can also specify hardcoded colours if you'd choose. In /resources/views/charts/, we must now create an index.blade.php file and add the following (depending on your blade setup and layout; here is an example): Laravel Chart Example Chart Demo Finally, we need to add the following to /routes/web.php: Route::get('/charts', 'ChartController@index')->name('charts'); Go to at your-project-name.test/charts now. Although this should serve as a good starting point for your understanding of the fundamentals of charts and graphs in Laravel, you may refer to the Chart.js documentation for more details on customizing your charts. Read the full article
0 notes
xceltecseo · 3 years ago
Text
What are the Key Features of the Laravel?
Tumblr media
As a more sophisticated alternative to the CodeIgniter framework, which lacked features like built-in user authentication and authorisation, Laravel was initially developed. When we refer to Laravel's original release, we mean the beta version, which was made available on June 9, 2011, and Laravel 1, which was made available later that month. Laravel 1 was regarded as the best option for websites or applications because it has built-in support for authentication, localization, models, views, sessions, routing, and many more techniques.
Construction of a database table is made possible by Laravel's crucial migration feature. It enables you to modify and distribute the application's database schema. A new column can be added to the table, or an existing one can be eliminated.
Faker is a PHP (Laravel) testing tool that creates fictitious data. Using Faker, you can produce as much test data as you require. The Laravel framework includes Faker. Faker can also be used on your own PHP-based websites or in other frameworks.
A method for automatically adding dummy data to the database is provided by Laravel. The process is referred to as seeding. Developers may quickly add test data to their database table by using the database seeder. By testing with different data formats, it enables developers to identify problems and maximise efficiency, which is quite helpful.
The important distinction in this case is how this release increased Laravel's popularity. Laravel is available in versions 1, 2, 3, 4, 5, 5.1, 5.3, 5.4, 6, 7, and most recently, Laravel 9.
The following are the most important features of Laravel 4.
Database seeding is used to initially populate databases.
There is built-in support for sending a variety of email formats.
There is support for the message queue.
support for the deletion of database records after a predetermined period of time (Soft deletion).
The following are the most important features of Laravel 5.
You can schedule jobs to be executed on a regular basis using the scheduler programme.
An abstraction layer called Flysystem makes it possible to use remote storage in the same way that local file systems are used.
External authentication can be handled more easily with the help of the optional Socialite package.
Package asset management is better with Elixir.
A new internal directory tree structure has been made for produced programmes.
Additionally, version 5.1 was updated.
The following are the most important features of Laravel 8.
Laravel's Jetstream module is used.
In the model factory, classes.
Migratory suffocation
Use Tailwind CSS for usability improvements such as pagination views.
Do you want to learn how to utilise Laravel? Knowledge and tools required
Intermediate understanding of PHP
HTML and CSS fundamentals
An excellent code editor (IDE)
Firefox is an example of a browser.
The following are the most important features of Laravel 9.
PHP Minimum Requirement
Migration of an Anonymous Stub
The Query Builder Interface has been updated.
String Functions in PHP 8
Conclusion
Here we have learned the essential parameters that are required for the Laravel website development using the varieties of Laravel Technologies.
Visit to explore more on What are the Key Features of the Laravel?
Get in touch with us for more! 
Contact us on:- +91 987 979 9459 | +1 919 400 9200
Email us at:- [email protected]
0 notes
entlizm · 5 years ago
Link
via PHPタグが付けられた新着記事 - Qiita
0 notes
rafi1228 · 6 years ago
Link
Build a RESTful API for a market system using Laravel and dominates the challenging RESTful skills with Laravel
What you’ll learn
Create your own projects with Laravel (not only RESTful APIs)
Make the most of your work tools (Sublime Text 3, Git, Github, Composer, PHP artisan and Laravel)
Generate and maintain the structure of the database in an automated way with Laravel and the PHP Artisan console
Use PHP Artisan effectively and be much more efficient
Create and configure your own local development environment
Properly configure your development environment for all your projects
Hone the main HTTP methods/verbs for HTTP and RESTful APIs
Use free professional tools to improve your productivity
Requirements
Very recommended a fundamental domain of Object Oriented Programming
Fundamental knowledge about PHP (classes, functions, methods, traits, inheritance)
Description
So you need to build a RESTful API for a project, but you do not know even where to start? Do not worry I will guide you through the whole process to build a genuine RESTful API using Laravel.
Join the more than 3000 students already taking this course, building their RESTful APIs using Laravel, and enjoying every single class!
Build a RESTful API for a marketplace system using Laravel. With Laravel creating every component will be a breeze; you will have a project with users, sellers, buyers, transactions, products and categories. Explore all types of relationships, one to many, many to many and much much more using Eloquent the Laravel ORM.
The comprehensive guide to creating a truly RESTful API with Laravel. You can follow the course using Laravel 5.5 (the latest Laravel version).
You will not find a Laravel course like this anywhere else. This course explains everything you need to develop a RESTful API using Laravel framework.
At the end of the course you will have a RESTful API with Laravel, for a market system, where users can purchase and sell different products with different categories and transactions. Inclusive, a same user can be both a seller and a buyer (you will take advantage of inheritance for this).
¡Do Not wait anymore! Become a master in the development of genuinely RESTful APIs with Laravel. Join the course now and see you in class
Remember: The course has been updated to use the latest version of Laravel (Laravel 5.5). Enjoy!
In this course, you learn how to develop a realistic,  fully implemented, and professional RESTful API with Laravel.
Laravel is the most popular PHP framework, with more than 20 million downloads along with lots of enterprise and personal projects worldwide. Additionally, includes fantastic features to implement a RESTful API easily. Laravel is RESTful friendly.
What is a RESTful API?
A Web API is like a web service which works entirely with HTTP. A RESTful API must follow the REST (REpresentational State Transfer) practices, allowing to orientate the design to the resources, provide standard responses based on the different status codes HTTP provide and provide according to Hypermedia Links in responses.
Why Laravel?
Because Laravel is a framework made by programmers for programmers, expressive, simple, intuitive and powerful. Laravel provides useful features for web projects including RESTful APIs.
Each new Laravel version includes many changes that make this framework even better, simple, programmer friendly and at the same time much more powerful. In fact, the latest versions of Laravel included a lot of new features to help to develop RESTful APIs in the right way.
During this course, you will master the complete structure of Laravel, along with the new features included in the latest version of Laravel to develop an actual RESTful API.
You will learn this about the development of a RESTful API with Laravel:
Using the Laravel PHP artisan for code and components generation
Usage and creation of middleware on Laravel
The Laravel Resource routes and controllers (ideal for RESTful APIs)
Fully supported JSON format responses for a JSON RESTful API
Validation of requests directly from the Laravel Controllers
Handling all types of exceptions and errors from Laravel handler
Complex operations involving up to three resources/models for a specific operation
Usage of Laravel dependency injection and model binding
Generation of the database structure using Laravel migrations
Automatic insertion of fake data into the database through “faker,” using Laravel factories, and seeders
Laravel Sessions and access_token access for the RESTful API. Yes Both!
Using Laravel Passport to protect the RESTful API with OAuth2
Pagination of results using Laravel collections
Using URL parameters to execute actions (the RESTful approach)
Sorting results based on URL parameters with a RESTful approach
Filtering results using URL parameters
Caching responses using Laravel Cache System
Limitation of requests using the Laravel middleware
Implementing HATEOAS on Laravel (a pure RESTful API must use HATEOAS)
Using PHP Fractal for transforming responses
Usage of CORS on the API responses to allow JavaScript-based clients and web browsers.
Use the Laravel Policies and Gates to handle the user’s authorization layer.
Much more!!
You can take a look at the full list of contents below. You will finish with a complete RESTful API and understanding a lot of Laravel skills.
You will create an actual RESTful API from scratch and step by step using Laravel. Follow the REST architecture and build appropriate URLs to identify actions and resources using the Laravel best features and learn Laravel in the way.
Take full advantage of tools like Sublime Text 3, Git, power shell, Laravel, Composer, PHP artisan, and be more productive for agile development.
Note: In few classes of the course I use Windows (only for the first classes), but I included specific directions in the case you use Linux or Mac and all the tools used are cross-platform, so you will no have any problem.
You will have lifetime access to the current classes and the classes that I will regularly add (take a look at the last section to see what is coming).
At the end of this course, you will be able to develop your pure RESTful API with Laravel in an efficient way with the best practices, taking advantage of the facilities provided by Laravel for the proper implementation of your projects and your RESTfulAPI.
Do not wait any longer. Join the course and see you in classes.
Who this course is for:
This course is for all web development and PHP lovers
This course is for all those who need to develop their own API completely RESTful
If you want to build your own fully functional and step-by-step RESTful API
If you need to keep your skills up to date and be competitive
If you want to do a complete development of your projects and your RESTful API with Laravel
Created by JuanD MeGon Last updated 3/2019 English Italian [Auto-generated]
Size: 2.24 GB
   Download Now
https://ift.tt/2qCGwoh.
The post RESTful API with Laravel: Build a real API with Laravel appeared first on Free Course Lab.
0 notes
krsrk · 8 years ago
Text
Integración Vue Js con Laravel 5.4 (1)
En esta publicación se verá la integración de Laravel con Vue Js. Vue Js es una librería de Js que se incluye en Laravel a partir de la versión 5.4. Esta versión su futuro será controlar la vista en Laravel. Pero además de que está integrado en Laravel esta librería une las características importantes de Angular y React.
Para ver cómo se integra con Laravel usaremos un caso escenario de un blog donde veremos en la vista principal las publicaciones hechas por el usuario y cuando se autentifique el usuario verá sus publicaciones propias. Así como también generamos un formulario para dar de alta una publicación, no abordaremos la totalidad del CRUD ya que simplemente esta publicación se trata de Vue Js y cómo vamos a procesar los datos en la vista.
Asumimos que el lector ya está relacionado con Laravel y no daremos detalles sobre código y comandos que se vean de Laravel. También asumimos que el lector ya está familiarizado con el entorno Homestead y como crear un dominio para este entorno.
Antes de Empezar
Tener instalado Node Js
Tener instalado Composer
Tener instalado el comando laravel en las globales del sistema
Tener instalado Homestead o un entorno MAMP o LAMP
Instalación del proyecto Laravel
Abrimos la terminal, nos logeamos a nuestro entorno Homestead via SSH, adentro del servidor navegamos a la carpeta Code o cualquiera que hayan puesto en default en la configuracion del Homestead, y simplemente ejecutamos el siguiente comando:
laravel new blog
Revisamos que nuestra aplicacion se creo realmente: http://blog.app. Si vemos la pantalla de bienvenida de Laravel ya tenemos nuestro proyecto creado.
Creación de Migraciones
En este paso crearemos nada más una migración que es la tabla de posts que ahí vamos almacenar las publicaciones hechas por el usuario. Para este paso usaremos otro comando para crear dichas migraciones. Tenemos que estar en el directorio del proyecto osea Code/blog :
php artisan make:migration create_table_feeds
Una vez ejecutado este comando nos creará un archivo en la ruta blog/database/migrations. Aquí crearemos código para nuestra estructura de la tabla. Antes que nada configuramos el .env con nuestra base de datos llamada blog.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTableFeeds extends Migration {    protected $tableName = 'feeds';    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create($this->tableName, function (Blueprint $table) {            $table->increments('id');            $table->integer('user_id');            $table->string('title');            $table->string('content');            $table->timestamps();            $table->integer('status')->default(1)->comments('1=publicacion activa, 2=en borrador o no publicda, 3=borrada');        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::dropIfExists($this->tableName);    } }
Creación de Modelos
Vamos a crear un modelo, para eso simplemente crearemos el modelo que nos falta ya que User ya esta por default cuando se crea el proyecto, ejecutamos:
php artisan make:model Feeds
Una vez que se ejecuta nos creará un archivo el cual reside en el directorio  /app llamado Feeds.php. Abrimos el archivo y codificamos lo siguiente:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Feeds extends Model {    /**     * The attributes that are mass assignable.     *     * @var array     */    protected $fillable = [        'user_id', 'title', 'content', 'status'    ]; }
Para crear una relacion en el modelo, revisaremos la lógica de nuestra app, como es de blog o de publicaciones, la cardinalidad es de 1 usuario -> varias publicaciones, entonces tendremos que modificar el modelo User y hacer lo siguiente dentro del codigo de la clase y agregar este metodo:
public function feeds() {    return $this->hasMany('App\Feeds'); }
Siguiente modificamos el modelo Feeds para establecer la relacion inversa:
public function user() {    return $this->belongsTo('App\User'); }
Creación de Factories
Los Factories se encuentran en /database/factories modificaremos el archivo ModelFactory.php y pondremos esto:
$factory->define(App\Feeds::class, function (Faker\Generator $faker) {    return [        'title' => $faker->sentence(6),        'content' => $faker->text,    ]; });
En el archivo ya existia el factory de Users. Este codigo marcara error si por ejemplo no se define las relaciones entre modelos. Usa la clase Faker para generar información aleatoria a la hora de crear los registros en la base de datos.
Creación de Seeds
Para crear los Seeds necesitaremos crear un Seed de Users con Feeds, para esto ejecutamos en la terminal:
php artisan make:seed UserTableSeeder
Una vez ejecutado este comando nos creará un archivo php UserTableSeeder en el directorio /database/seeds; abriremos el archivo y codificamos lo siguiente:
<?php use Illuminate\Database\Seeder; class UserTableSeeder extends Seeder {    /**     * Run the database seeds.     *     * @return void     */    public function run()    {        factory(\App\User::class, 6)->create()->each(function ($u) {            $u->feeds()->saveMany(factory(\App\Feeds::class, 2)->create(['user_id' => $u->id]));        });    } }
Abrimos el archivo DatabaseSeeder y codificamos lo siguiente:
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder {    /**     * Run the database seeds.     *     * @return void     */    public function run()    {        $this->call(UserTableSeeder::class);    } }
Una vez teniendo listo nuestros archivos ejecutamos los siguientes comandos:
php artisan migrate
php artisan  db:seed
Una vez hecho esto se deberá tener la tabla feeds y users con registros.
Creación de un sistema de autentificación
Para crear un sistema de autentificación en Laravel simplemente ejecutaremos:
php artisan make:auth
Probamos nuestros usuarios; nos dirigimos a http://blog.app/login y entramos la información de algun usuario, el password es secret. Si se puede logear ya está listo nuestro sistema de autentificación.
0 notes
fooyay · 8 years ago
Text
Returning to the BusinessTest
With some more advanced tools in place, it is time to revisit my efforts with the BusinessTest class.
The first thing to do is to add a factory for the Business model. Using the User factory as an example, I’m able to create a factory to create businesses for use in tests.
$factory->define(App\Business::class, function (Faker\Generator $faker) {    return [        'name' => $faker->company,        'zip_code' => $faker->postcode,        'active' => true,        'created_at' => Carbon::now(),        'updated_at' => Carbon::now(),    ]; });
This appears in ModelFactory.php. I looked over the schema for the table to confirm that each of the attributes is covered. I also added “use Carbon/Carbon;” at the top.
I then moved BusinessTest.php into the tests/integration/models directory. I added support for DatabaseTransactions as well, like in the UserTest.php file. Then I tried to write a test for the slug. This returned the following error: “InvalidArgumentException: Unable to locate factory with name [default] [App\Business].” Once again, Laravel is returning an obscure error. After chasing various red herrings related to namespaces, I started removing bits of the file until it looked more and more like UserTest.php. Ultimately, it turned out that with TestCase, the setup() function needs to call parent::setup(). It also needs special handling to deal with the database transactions.
I set that aside for now. Perhaps with the factories, the need for a setup() is no longer as important. So I removed the setup and continued.
/** @test */ function a_business_has_a_slug() {    $business = factory(Business::class)->create(['name' => 'Dan\'s 12 Amazing Donkeys & Donuts']);    $this->assertEquals('dans-12-amazing-donkeys-donuts', $business->slug()); }
Without setup() breaking things, this test passed green. The factory doesn’t set a value for slug, so I know that the model is doing the work here, as it should.
Next, I can test that hasEmployee($user) returns false when a company has no employees and $user is null.
function test_a_null_is_not_an_employee_in_a_business_with_no_employees() {    $nullUser = null;    $noEmployeesBusiness = factory(Business::class)->create();    $this->assertFalse($noEmployeesBusiness->hasEmployee($nullUser)); }
Again, setup is disabled here, so I created a business using the factory. This test passes.
To test the scenarios where a business has employees, I will need to create objects for User, Business, and Employee with the correct foreign keys, and that’s where I will turn my focus tomorrow.
0 notes
mbaljeetsingh · 8 years ago
Text
Implement a Favoriting Feature Using Laravel and Vue.js
These days, various web applications are in one way or the other implementing a kind of favorite/like/recommend feature on the websites. These can be seen on sites like Medium, Facebook, Laracasts, and even here on scotch.io and school.scotch.io.
In this tutorial, I'll be showing you how to implement a favorites feature using Vue.js in your Laravel application. Though we'll be using the term favorites in this tutorial, this can be replaced with likes, recommends depending on your application.
What We'll Be Building
We'll be building a simple Posts app. This app will comprise of users and posts. Users will be able to create posts and as well mark posts as favorites. Finally, users will be able to see all the posts they marked as favorites.
The app will have a User model and a Post model, there will be an authentication system which will allow only authenticated users mark/unmark posts as favorites. We'll make use of VueJs and Axios to make marking/un-marking posts as favorites dynamic, that is without reloading the page.
Before we start building, let's take a quick look at what the Posts app will look like when we are done.
Let's Get started
We'll start by creating a new Laravel project, the name of the project will be laravel-vue-favorite.
laravel new laravel-vue-favorite
This will create a new Laravel 5.4 (which is the current version as at the time of this tutorial) project.
Installing NPM Dependencies
In a fresh installation of Laravel, Laravel provides some frontend frameworks and libraries with some basic setup to integrate these packages together. Among the frameworks and libraries are Bootstrap, VueJs and Axios, which we will be using in this tutorial. But we still need to install these dependencies through NPM:
npm install
Also, we'll make use of Laravel Mix to compile and build our CSS and JavaScript. The command above will also install all Laravel Mix dependencies.
Models And Migrations
For our Posts app, we'll need a User model (which comes with Laravel), a Post model and a Favorite model and their respective migration files.
php artisan make:model Post -m php artisan make:model Favorite -m
These will create a Post model and a Favorite model along with their migration files respectively. Open the posts table migration file and update the up() with:
/** * Define posts table schema */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('title'); $table->text('body'); $table->timestamps(); }); }
The posts table will contain an id, user_id (ID of the user that created the post), title, body, and some timestamps columns.
Next, open the favorites table migration file and update the up() with:
/** * Define favorites table schema */ public function up() { Schema::create('favorites', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->integer('post_id')->unsigned(); $table->timestamps(); }); }
The favorites table will be a pivot table. It will contain two columns: user_id which will hold the ID of the user that favorited a post and post_id which will the ID of the post that was favorited.
For the users table migration, we'll be using the default Laravel provided.
Before we run our migrations, let's setup our database. Add your database details to the .env file:
DB_DATABASE=laravue DB_USERNAME=root DB_PASSWORD=root
Remember to update with your own database details. Now we can go on and run our migrations:
php artisan migrate
Database Seeder
We'll also generate some seed data which we can test our app with. To generate dummy data, we'll make use of Laravel Model Factories. Laravel model factories make use of the Faker PHP library.
We'll generate dummy data of Users and Posts. When you open the database/factories/ModelFactory.php file, you will see that Laravel provides a User model factory, which means we only need to create a Post model factory. Add the snippets below to database/factories/ModelFactory.php just after the User model factory:
// database/factories/ModelFactory.php $factory->define(App\Post::class, function (Faker\Generator $faker) { // Get a random user $user = \App\User::inRandomOrder()->first(); // generate fake data for post return [ 'user_id' => $user->id, 'title' => $faker->sentence, 'body' => $faker->text, ]; });
Let's quickly run through the code. Remember from our posts table migration, we defined that a post must have a user ID. So, we get a random user and assign the user_id of a post to the ID of the random user, then we use Faker to generate the title and body of the post.
With our model factories done, let's move on to create our database seeder classes by running these commands:
php artisan make:seeder UsersTableSeeder php artisan make:seeder PostsTableSeeder
Open database/seeds/UsersTableSeeder.php and update the run() with:
// database/seeds/UsersTableSeeder.php /** * Run the database seeds to create users. * * @return void */ public function run() { factory(App\User::class, 5)->create(); }
This will create 5 different users with dummy data when the seeder is run. We'll do the same for Posts. Open database/seeds/PostsTableSeeder.php and update the run() with:
// database/seeds/PostsTableSeeder.php /** * Run the database seeds to create posts. * * @return void */ public function run() { factory(App\Post::class, 10)->create(); }
This will create 10 different posts with dummy data when the seeder is run.
Before we run the database seeders, let's update the database/seeds/DatabaseSeeder.php which is provided by default:
// database/seeds/DatabaseSeeder.php /** * Run the database seeds. * * @return void */ public function run() { $this->call(UsersTableSeeder::class); $this->call(PostsTableSeeder::class); }
Now we can run the database seeders:
php artisan db:seed
You should now see some dummy data in your database.
Authenticating Users
Before a user can mark a post has favorite, the user must be logged in. So we need a kind of authentication system. Luckily for us, Laravel got our back on this. We'll use the artisan make:auth command to scaffold an authentication system.
php artisan make:auth
This will create all of the necessary routes and views for authentication. We can go and register as a user, which we will use to test the functionality of the application we are building.
Defining Our Routes
Let's define the routes of our application. Open routes/web.php and update with below:
// routes/web.php Auth::routes(); Route::get('/', 'PostsController@index'); Route::post('favorite/{post}', 'PostsController@favoritePost'); Route::post('unfavorite/{post}', 'PostsController@unFavoritePost'); Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');
The routes are pretty straightforward. Auth routes that Laravel created when we ran the make:auth command. A route to the homepage that will list all posts, two other routes for favoriting and unfavoriting posts. Lastly, a route that displays all posts that have been marked as favorites by a user. This route will be accessible to only authenticated users.
When a user registers or login, Laravel will redirect them to the /home route by default. Since we have removed the /home route that Laravel created when we ran make:auth. We need to update the redirectTo property of both app/Http/Controllers/Auth/LoginController.php and app/Http/Controllers/Auth/RegisterController.php to:
protected $redirectTo = '/';
Defining Users To Favorite Posts Relationship
Since a user can mark many posts as favorites and a post can be marked as favorites by many users, the relationship between users and favorite posts will be a many to many relationships. To define this relationship, open the User model and add a favorites():
// app/User.php /** * Get all of favorite posts for the user. */ public function favorites() { return $this->belongsToMany(Post::class, 'favorites', 'user_id', 'post_id')->withTimeStamps(); }
Laravel will assume the pivot table is post_user but since we gave the pivot table a different name (favorites), we have to pass in some additional arguments. The second argument is the name of the pivot table (favorites). The third argument is the foreign key name (user_id) of the model on which you are defining the relationship (User), while the fourth argument is the foreign key name (post_id) of the model that you are joining to (Post).
Noticed we chained withTimeStamps() to the belongsToMany(). This will allow the timestamps (create_at and updated_at) columns on the pivot table be affected whenever a row is inserted or updated.
Posts Controller
Let's create a new controller that will handle displaying posts, marking a post as favorite and unfavorite a post.
php artisan make:controller PostsController
Open the newly created app/Http/Controllers/PostsController.php and add the snippet below to it:
// app/Http/Controllers/PostsController.php // remember to use the Post model use App\Post; /** * Display a paginated list of posts. * * @return Response */ public function index() { $posts = Post::paginate(5); return view('posts.index', compact('posts')); }
The index() will get all posts and paginate them into 5 per page. Then render a view file (that we are yet to create) along with the posts, which will do the actual displaying of the posts.
Remember when we ran make:auth command that Laravel created some views. We'll be using the resources/views/layouts/app.blade.php that was created and make some few additions to it. Add the code below just after the <title>:
// resources/views/layouts/app.blade.php <link rel="stylesheet" href="http://ift.tt/2mrbfp2; />
Then add this just before the Logout list item:
// resources/views/layouts/app.blade.php <li> <a href="http://ift.tt/1uaQUM0">My Favorites</a> </li>
Now let's create the index view. Create a new posts folder within views directory and create a new index.blade.php file within the newly created folder. Paste the code below into resources/views/posts/index.blade.php:
// resources/views/posts/index.blade.php @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="page-header"> <h3>All Posts</h3> </div> @forelse ($posts as $post) <div class="panel panel-default"> <div class="panel-heading"> </div> <div class="panel-body"> </div> </div> @empty <p>No post created.</p> @endforelse </div> </div> </div> @endsection
Pretty simple markup that displays a paginated list of posts. Open the homepage in your browser, you should see page like the image below:
Next, let's go back to PostsController and add the methods that will handle marking a post as favorite and unfavorite a post. Add the code below to PostsController:
// app/Http/Controllers/PostsController.php // remember to use use Illuminate\Support\Facades\Auth; /** * Favorite a particular post * * @param Post $post * @return Response */ public function favoritePost(Post $post) { Auth::user()->favorites()->attach($post->id); return back(); } /** * Unfavorite a particular post * * @param Post $post * @return Response */ public function unFavoritePost(Post $post) { Auth::user()->favorites()->detach($post->id); return back(); }
The favoritePost() takes a post as an argument. Using the favorites relationship we defined above, we attach the post ID to the ID of the authenticated user then insert into the favorites table. Finally, return back to the previous page.
The unFavoritePost() is the reverse of favoritePost() which simply remove the ID of the authenticated user along with the post ID from the favorites table.
Integrating With VueJs
It's time to integrate Vue into our application. We'll make the favorite button/icon a Vue component. Making it a Vue component will allow for reuse in multiple places with our application.
Once the favorite button/icon is clicked, we'll mark the post as favorite or unfavorite without reloading the page, that is through AJAX. For this, we'll make use of Axios which is a Promise based HTTP client for the browser and node.js.
Creating The Favorite Component
Create a new Favorite.vue file within the resources/assets/js/components folder and paste the code below into it:
// resources/assets/js/components/Favorite.vue <template> <span> <a href="#" v-if="isFavorited" @click.prevent="unFavorite(post)"> <i class="fa fa-heart"></i> </a> <a href="#" v-else @click.prevent="favorite(post)"> <i class="fa fa-heart-o"></i> </a> </span> </template> <script> export default { props: ['post', 'favorited'], data: function() { return { isFavorited: '', } }, mounted() { this.isFavorited = this.isFavorite ? true : false; }, computed: { isFavorite() { return this.favorited; }, }, methods: { favorite(post) { axios.post('/favorite/'+post) .then(response => this.isFavorited = true) .catch(response => console.log(response.data)); }, unFavorite(post) { axios.post('/unfavorite/'+post) .then(response => this.isFavorited = false) .catch(response => console.log(response.data)); } } } </script>
The Favorite component has two sections: template and script. In the template section, we defined the markup that will be rendered when the component is used. We are using conditional rendering to show the appropriate button/icon. That is, if isFavorited is true, the button/icon should be marked as favorite and on click of the button/icon should trigger unFavorite(). Else the button/icon should be marked as unfavorite and on click of the button/icon should trigger favorite().
Moving on to the script section, we defined some properties for the component; post (will be the ID of the post) and favorited (will either be true or false depending on if the post has been favorited by the authenticated user). We also defined an isFavorited data which will be used for the conditional rendering from above.
When the component is mounted, we set the value of isFavorited to the value of isFavorite computed property. That is, the isFavorite computed property will return the value of favorited prop which will either be true or false. We use a computed property so as to reactively get the value of the favorited prop instead using the value of favorited prop that was passed directly.
Lastly, we defined two methods: favorite() and unFavorite() which both accepts the post prop as arguments. Using Axios, we make a POST request to the routes we defined earlier. For the favorite(), once the POST request is successful, we set isFavorited to true and otherwise console log the errors. Same is applicable to the unFavorite() just that we set isFavorited to false.
Registering The Favorite Component
Before we can start to use the Favorite component, we need to first register it on our Vue root instance. Open resources/assets/js/app.js, you will see that Laravel register an Example component. We are going to replace that with the Favorite component:
// resources/assets/js/app.js Vue.component('favorite', require('./components/Favorite.vue'));
Now we can compile and build our styles and scripts:
npm run dev
Using The Favorite Component
We can now use the Favorite component. Open resources/views/posts/index.blade.php and add the snippets below to it after the closing div of the panel-body:
// resources/views/posts/index.blade.php @if (Auth::check()) <div class="panel-footer"> <favorite :post= :favorited= ></favorite> </div> @endif
The favorite button/icon will only be displayed to authenticated users. As you can see, we passed to the Favorite component the props that we defined when we created the component. To know if a post is has been favorited by the authenticated user, we call a favorited() (which we are yet to create) on the post.
To create favorited(), open app/Post.php and add the code below to it:
// app/Post.php // remember to use use App\Favorite; use Illuminate\Support\Facades\Auth; /** * Determine whether a post has been marked as favorite by a user. * * @return boolean */ public function favorited() { return (bool) Favorite::where('user_id', Auth::id()) ->where('post_id', $this->id) ->first(); }
This gets and casts to boolean the first result where the user_id is equal to that of the authenticated user and where the post_id is equal to the ID of the post the method is called on.
If you visit the homepage of the application in the browser and login, you should get something similar to:
As you can see I have marked some posts as favorites.
Displaying User Favorite Posts
Won't it be nice for users to be able to see all the posts they have marked as favorites? Sure it will be. Remember we defined a my_favorites route that will be accessible to only authenticated users, this is where users will be able to see the posts they've marked as favorites.
Let's create a UsersController that will handle this route.
php artisan make:controller UsersController
Open app/Http/Controllers/UsersController.php and add the code below to it:
// app/Http/Controllers/UsersController.php // remember to use use Illuminate\Support\Facades\Auth; /** * Get all favorite posts by user * * @return Response */ public function myFavorites() { $myFavorites = Auth::user()->favorites; return view('users.my_favorites', compact('myFavorites')); }
The myFavorites() uses the favorites relationship we defined earlier, get all the posts that the authenticated user has marked as favorites. Then return a view along with favorites posts.
Now let's create the view. Create a new users folder within the resources/views directory and within the users folder, create a new file my_favorites.blade.php and paste the code below to it:
// resources/views/users/my_favorites.blade.php @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="page-header"> <h3>My Favorites</h3> </div> @forelse ($myFavorites as $myFavorite) <div class="panel panel-default"> <div class="panel-heading"> </div> <div class="panel-body"> </div> @if (Auth::check()) <div class="panel-footer"> <favorite :post= :favorited= ></favorite> </div> @endif </div> @empty <p>You have no favorite posts.</p> @endforelse </div> </div> </div> @endsection
The markup is similar to that of index.blade.php. As you can see, we also used the Favorite component. When viewed in the browser, you should see something similar to:
Conclusion
That's it, we are done building the Post app and seen how to allow only authenticated users mark/unmark posts as favorites without reloading the page using VueJs and Axios. I hope you find this tutorial useful. If you encounter any problems following this tutorial or have questions/suggestions, kindly drop them in the comment section below. Also, I have made a vue-favorite component based on this tutorial which can be installed through NPM.
via Scotch.io http://ift.tt/2mptpr0
0 notes
krsrk · 8 years ago
Text
Creación de una web app con Laravel 5.3 [Base de Datos: Factories y Seeds] (5)
Creación de Factories
Factories es un componente de Laravel el cual su función es popular la base de datos con información, obviamente esta información es de prueba o no verídica; se usa principalmente para pruebas o para iniciar una base de datos con datos.
Para empezar a codificar un factory debemos ir al directorio  “database/factories”, una vez en ese directorio abriremos  el archivo “ ModelFactory.php” y pondremos lo siguiente:
<?php use App\User; use Faker\Generator as FakerGen; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(User::class, function (FakerGen $faker) {    $fields = [    'name' => $faker->name,    'email' => $faker->email,    'password' => bcrypt('secret'),];            return $fields; }); ///Factory para la tabla post $factory->define(App\Post::class, function (Faker\Generator $faker) {    return [        'title' => $faker->sentence(5),   'abstract' => $faker->sentence(15),        'content' => $faker->text(),    ]; }); ///Factory para la tabla post_comment     $factory->define(App\PostComment::class, function (Faker\Generator $faker) {    return [        'comment' => $faker->sentence(15),    ]; });
Se va generar información en la base de datos por cada tabla que tengamos en este caso tenemos 3 tablas user, post, post_comment.Factories usa una clase que se llama FakerGen la cual es encargada de generar la información aleatoria.
Al método “define” le pasaremos las clases de los modelos(esto lo definiremos mas adelante) y un callback con el parametro del FakerGen; adentro de este callback las opciones del FakerGen.
Creación de Seeds
En esta instancia de Laravel ejecutaremos nuestro Factories para que se genere la información, estos archivos generados se encuentran en “database/seeds” y cuentan con el metodo run() el cual aquí haremos nuestras llamadas a los factories, una vez localizado el seed lo abriremos y escribiremos lo siguiente en el metodo run(), abriremos primero PostTableSeeder.php:
<?php use Illuminate\Database\Seeder; class PostTableSeeder extends Seeder {    /**     * Run the database seeds.     *     * @return void     */    public function run()    {        factory(\App\Post::class, 10)->create()->each(function($p) {            $p->comments()->saveMany(factory(\App\PostComment::class, 5)->make());   });    } }
En este código en el método run() le indicaremos cuantos registros queremos esto lo definimos en primer parámetro de factory; después por cada uno de estos registros va generar 5 comentarios definidos en el parámetro del método saveMany(). Con esto tendremos 10 publicaciones o post y 5 comentarios por cada una de estas publicaciones. Esto seria el código de la tabla de User:
<?php use Illuminate\Database\Seeder; class UserTableSeeder extends Seeder {    /**     * Run the database seeds.     *     * @return void     */    public function run()    {       factory('App\User', 5)->create();    } }
Con esto ya tenemos codificado nuestros Seeds y Factories, el próximo capitulo codificaremos nuestros Modelos para ejecutar todo este proceso.
0 notes