How to generate dummy images in PHP Laravel? - laravel-5

I want to make dummy data on my home page, including showing dummy images. How can I generate images?

In the factory method, while seeding, do something like this.
$factory->define(Post::class, function (Faker $faker) {
return [
'image'=>'https://source.unsplash.com/random',
];
});
Now every time when you run the factory to seed, it will put that link in the image field. This link will give you a random image each time from unsplash.
Simply add photo dimensions after the URL (ex: /800x600)

If you just want to look your homepage "live" with dummy images and without actually uploading the image, you can show random images using this site:
http://lorempixel.com/
<img src="http://lorempixel.com/400/200/sports/" />
You can also store that image path in the database while seeding.
Thanks

In the following turorial show how to add images in the seeder.
https://www.5balloons.info/faker-images-in-laravel/#
Use the following method:
'image' => $faker->image('public/storage/images',640,480, null, false),
<?php
/* #var $factory \Illuminate\Database\Eloquent\Factory */
use App\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
return [
'name' => $faker->word,
'short_description' => $faker->sentence,
'description' => $faker->paragraph,
'category_id' => function () {
return factory(App\Category::class)->create()->id;
},
'amount' => $faker->randomFloat(2, 0, 10000),
'image' => $faker->image('public/storage/images',640,480, null, false),
];
});

You could use faker to create a seeder file that places some dummy images into your database. Faker comes pre-installed with laravel.

May be it could help someone who wants to work with Ecommerce dummy product images -
public function definition()
{
$randomImages =[
'https://m.media-amazon.com/images/I/41WpqIvJWRL._AC_UY436_QL65_.jpg',
'https://m.media-amazon.com/images/I/61ghDjhS8vL._AC_UY436_QL65_.jpg',
'https://m.media-amazon.com/images/I/61c1QC4lF-L._AC_UY436_QL65_.jpg',
'https://m.media-amazon.com/images/I/710VzyXGVsL._AC_UY436_QL65_.jpg',
'https://m.media-amazon.com/images/I/61EPT-oMLrL._AC_UY436_QL65_.jpg',
'https://m.media-amazon.com/images/I/71r3ktfakgL._AC_UY436_QL65_.jpg',
'https://m.media-amazon.com/images/I/61CqYq+xwNL._AC_UL640_QL65_.jpg',
'https://m.media-amazon.com/images/I/71cVOgvystL._AC_UL640_QL65_.jpg',
'https://m.media-amazon.com/images/I/71E+oh38ZqL._AC_UL640_QL65_.jpg',
'https://m.media-amazon.com/images/I/61uSHBgUGhL._AC_UL640_QL65_.jpg',
'https://m.media-amazon.com/images/I/71nDK2Q8HAL._AC_UL640_QL65_.jpg'
];
return [
'name' => fake()->sentence(5),
'price' => fake()->randomFloat(2, 10, 1000),
'image' => $randomImages[rand(0, 10)]
];
}
For me, it's simply enough to get some real-dummy image for development test purpose.

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

How to convert object return by laravel model factory create method into array containing model fields?

For example, I have a UserFactory.php
<?php
use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'role' => 'USER',
'password' => 'sasdcsdf34', // password
'remember_token' => Str::random(10),
];
});
Now, I can create a user as following
$user = factory(User::class)->create();
Now, How can I convert this $user object into array containing user info like name,email etc without initializing new array and manually assigning every $user object property. ??
I DON'T want to manually assign like following as it is tedious if there are many properties in $user object
$userArray=[
'id' => $user->id,
'name' => $user->name,
'email' => $user->email
]
I have tried this but it creates array containing various other properties and actual values needed are nested inside properties
$userArray=array($user)
You should try using the raw method of factory instead of create.
$user = factory(User::class)->raw();
This should give you an array you can work with.
Try to add something like this to your model class:
public function getArr(){
foreach($this->attributes as $key => $val){
$array[$key] = $val;
}
return $array;
}
If you wish to have this function in every model you could create trait with this function and then just attach it in model class or any class extending it.
You can use json_decode.
// Laravel 7
$userArray = json_decode(factory(User::class)->create(), true);
// Laravel 8
$userArray = json_decode(User::factory()->create(), true);
For Laravel 8, instead of make or create method, use:
User::factory()->raw();
This will return an array

How in feature testing use data from factory?

In laravel 5.8 app with tests I make posting data with some dummy data, like:
$newVoteCategoryRow= [
'id' => null,
'name' => $new_vote_category_row_name,
'meta_description' => 'vote category meta_description on ' . now(),
'meta_keywords' => [ 'vote category meta_description on ' . now(), 'meta_keywords' ],
'active' => true,
'in_subscriptions' => true,
];
$response = $this->actingAs($loggedUser)->post('/admin/vote-categories', $newVoteCategoryRow);
$this->assertCount( $vote_categories_count+1, VoteCategory::all() );
it works ok, but actually I have factory for VoteCategory table in /database/factories/VoteCategoryFactory.php, defined :
<?php
use Faker\Generator as Faker;
use \Cviebrock\EloquentSluggable\Services\SlugService;
use App\VoteCategory;
$factory->define(App\VoteCategory::class, function (Faker $faker) {
$name= 'Vote category ' . $faker->word;
$slug = SlugService::createSlug(VoteCategory::class, 'slug', $name);
return [
'name' => $name,
'slug' => $slug,
'active' => true,
'in_subscriptions' => false,
'meta_description' => $faker->text,
'meta_keywords' => $faker->words(4),
];
});
and my question is if there is a way in post request instead of $newVoteCategoryRow array use my factory, not adding row in database but
reading data from factory for post request ?
to achieve that you just need to use your factory within the test case method:
to create VoteCategory u have to methods, the first one is make and this one will create an instance of VoteCategory without persisting it within the database, and the create method will persist the new VoteCategory within the database.
in your case, you want to create a new instance without adding it to the database, for that you just need to use make:
$newVoteCategoryRow = factory('App\VoteCategory')->make(); // add this line to your test case method.
$response = $this->actingAs($loggedUser)->post('/admin/vote-categories', $newVoteCategoryRow->toArray());
$this->assertCount( $vote_categories_count+1, VoteCategory::all());
for more information, you can check the doc Laravel 5.8: using-factories

How to Use a Slug for a URL

I am trying to use slugs as a way to display links on my URL. For example instead of using:
http://localhost:8000/product/1
I want to use...
http://localhost:8000/product/blue-shirts
So far I managed to add slugs via the package cviebrock/eloquent-sluggable. What should I use for my route and view?
<?php
use Sluggable;
public function sluggable()
{
return [
'slug' => [
'source' => 'product_name'
]
];
}

Add custom values in drop down in laravel backpack

I am using laravel back and and I have two tables called bundles and study. I added a drop down fields in the form from bundleCrudController. But I just want to add only those values in the drop down list which studies are created by the logged in user not all the data from studies table.
Here is my code to add data in drop down list -
$this->crud->addField([
'name' => 'studies',
'label' => 'Studies',
'type' => 'select2_from_array',
'options' => $this->Study->getUnallocatedStudies($entryId),
'allows_null' => false,
'hint' => 'Search for the studies you would like to add to this bundle',
'tab' => 'Info',
'allows_multiple' => true
]);
$this->crud->addColumn([
'label' => 'Studies',
'type' => "select_multiple",
'name' => 'bundle_id',
'entity' => 'studies',
'attribute' => 'name',
'model' => "App\Models\Study",
]);
So pls help me to resolve the problem to add only those records in the dropdownlist created by the logged in user not all records.. Thanx
I think the best way would be to create an additional model, UserStudy, that:
extends Study;
has a global scope for filtering for what the current user can see;
It should look something like this:
<?php
namespace App\Models;
use App\Models\Study;
use Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class UserStudy extends Study
{
/**
* The "booting" method of the model.
*
* #return void
*/
protected static function boot()
{
parent::boot();
// filter out the studies that don't belong to this user
if (Auth::check()) {
$user = Auth::user();
static::addGlobalScope('user_id', function (Builder $builder) use ($user) {
$builder->where('user_id', $user->id);
});
}
}
}
You'll then be able to use this UserStudy model in your field definition, instead of Study. Just replace App\Models\Study with App\Models\UserStudy.
Hope it helps. Cheers!

Resources