Insert image in database using faker library - php

Factory Class
$factory->define(Product::class, function (Faker $faker) {
return [
'image' => url("/images/{$faker->image('public/storage/images',640,480, null, false)}")
];
});
And after this command
php artisan db:seed
image column of database filled with this string
http://localhost/images/a1af4cb757aef7f6b181dfb978228767.jpg"
and when i seach this url on browser, i get "Unable to connect" error

You need to add storage in your link before images/image_name to be like this
http://localhost/storage/images/a1af4cb757aef7f6b181dfb978228767.jpg
Make sure that you run php artisan storage:link

Related

test artisan command laravel 9

I'm trying to write a test command in Laravel 9. In the below code the new user will create successfully But after creating need to redirect the Dashboard page
public function test_an_action_that_requires_authentication()
{
$user = $this->artisan('make:user',[
'name' => "username",
'email' => "useremail",
'password' => Str::random(8)
]);
}
How to redirect to the route after success created
We will use the assertExitCode method to assert that the command completed with a given exit code.
$this->artisan('module:import')
->expectsConfirmation('Do you really wish to run this command?', 'no')
->assertExitCode(1);
for more information you can find here
https://laravel.com/docs/9.x/console-tests
N.B. This code does not work in test. You can not redirect in an artisan command.
Said that, in laravel, to redirect to the home page, you can use this code in a controller function:
return redirect(url('/'));

Why a merged namespace is created instead of a submodule?

I added my module for creating blanks migration, views, controllers, etc.;
private function createModel()
{
$model = Str::singular(Str::studly(class_basename($this->argument('name'))));
$this->call('make:model',[
'name' => "App\\Modules\\".trim($this->argument('name'))."\\Models\\".$model
]);
}
After running the
php artisan make:module Admin\Users --model --controller
command in the console, I get the wrong structure (pic1)

Image doesn't save in public folder laravel

I'm learning laravel but I have problem now with the image,
I want it to save it in storage/app/public/avatar so I can show it, but it keep saving it in storage/app/avatar
I write this in the .env
FILESYSTEM_DRIVER=public
And then I generate the storage link
php artisan storage:link
but still the same, every time I upload a photo it saving it in storage/app/avatar
Anyone can help me?
In filesystems.php
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
Here :
$attributes['avatar'] = request('avatar')->store('public/avatars');
In USer.php
public function getAvatarAttribute($value)
{
return asset($value);
}
this method was working correctly when i was using a random avatar link,
but now it show nothing, i check my database and the link is there and it's right
public function getAvatarAttribute($value)
{
asset('storage/avatars/'.$image->name);
}
$attributes['avatar'] = request('avatar')->store('public/avatars');
In the controller, update method:
$user->update($attributes);
$user->password = Hash::make($user['password']);
$user->save();
return redirect($user->path());
In the show.blade
<img
src= "{{ $user->avatar }}"
alt=""
class="rounded-full mr-4 absolute"
style="width: 150px; left: calc(50% - 75px); top: 300px"
>
but the src become "(unknown)"
This looks more like a configuration cache issue as your filesystem looks properly configured.
The storage/app folder is the path of laravel's default disk (the local disk). Since you had specified to use public as the default disk in .env but your application is still using the local disk path, it looks like a cache issue
Try using
php artisan config:clear
And then attempt
request('avatar')->store('avatars');
If it was indeed a cache issue, then the file should be stored in the storage/app/public folder.
To get the full path to the image, use
Storage::url('avatar/'.$user->avatar);
So in the accessor, use
public function getAvatarAttribute($value)
{
return Storage::url('avatar/'.$value);
}
Using asset() to get the path to the file is not recommended because if some day you wish to switch storage to the cloud (S3, or any other storage. basically, you want to not use the storage folder of your application), then the asset() will no longer give you the correct path and you'd need to change it everywhere. But when using the storage facade, all you need to do is change it in the filesystems.php
Also, just to test it yourself, you could also specify the disk when storing by specifying the disk as the second argument to the store method
request('avatar')->store('avatars', 'public');
Storage::disk('public')->url('avatar/'.$user->avatar);
Also, don't forget to delete public/storage folder
and then re-run
php artisan config:clear
This is important
php artisan storage:link
Change "FILESYSTEM_DRIVER=public" to
FILESYSTEM_DISK=public
Or remove that line completely and directly set public folder as default disk in filesystems.php as follows:
'default' => env('FILESYSTEM_DISK', 'public'),
The store method stores the files in storage/app directory. That's why your code is storing the image in storage/app/avatars
request('avatar')->store('avatars');
This will place it under storage/app/public/avatars
request('avatar')->store('public/avatars');
To show it
asset('storage/avatars/`.$image->name)

Laravel Factory State- Unable to locate factory

I have a problem when executing the factory, i have used the factory state for factories but it will give me an error when i execute the factory
https://laravel.com/docs/5.6/database-testing#factory-states
I have this UserFactory.php which contains the code below.
<?php
use Faker\Generator as Faker;
$factory->state(App\User::class,'suggestor', function (Faker $faker) {
return [
'FirstName'=>$faker->firstName,
'LastName'=>$faker->lastName,
'Username'=>$faker->userName,
'password'=>bcrypt('123asd!##'),
'Email'=>$faker->email,
'AccountType'=>0,
];
});
i am using tinker to execute the factory commands and tried different syntax but it really does not solve the problem.
>>> factory(User::class, 1)->states('suggestor')->make();
[!] Aliasing 'User' to 'App\User' for this Tinker session.
InvalidArgumentException with message 'Unable to locate factory with name [default] [User].'
>>> factory(App\User::class, 1)->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>> factory(\App\User::class, 1)->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>> factory('App\User')->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>> factory('App\User',1)->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>>
i hope there's anyone out there can help me.
Update:
I have tried running it on database seed but i think it's still the same error.
but when i tried on the other model it seems fine. i think the problem is on the User model which comes out of the box by laravel and note that i haven't change anything on the user model except the model attributes.
error produce by seeder
As the error states, you need a default factory. Please compare the following two:
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'password' => bcrypt(str_random(10)),
'remember_token' => $faker->randomNumber(),
];
});
$factory->state(App\User::class, 'test_state', function (Faker\Generator $faker) {
return [
'name' => 'Namoshek',
'email' => 'namoshek#example.com',
];
});
The first definition is the default factory for users, when not giving a state. You can call them with factory(App\User::class, 10)->create() where 10 is optional to give the number of models to create.
You can also chain ->states('test_state') after the call to factory():
factory(App\User::class)->states('test_state')->create(), which will first run the default factory and then apply the changes defined by the given state on the model. But you always need a default factory, otherwise the system doesn't know where and what to apply the state to.
By the way, there is a difference between ->create() and ->make(). The latter does only create the models without persisting them in the database, whereas the first one persists them. So ->create() is equivalent to ->make()->save().
sometimes it also happens that factory works fine in web routes and tests but in tinker it behaves as it is mentioned above. In that case you can try to clear laravel application cache. here are the commmands.
php artisan cache:clear
php artisan config:clear
php artisan route:clear
this will clear all the caches. then i could create model instances using factory.
>>> factory(User::class)->create() // or
>>> factory(Book::class)->create()

run artisan command from php function

I want to run php artisan passport:client --password from function.
I tryed Artisan::call('passport:client'); and Artisan::command('passport:client'); but it return undefined command
Note: I have alredy install laravel passport and the command is working fine from the terminal
I have found it, in boot() method of the PassportServiceProvider there is a check that essentially prevent it being called from Artisan::call.
//PassportServiceProvider.php at line 37:
if ($this->app->runningInConsole()) {
$this->commands([
Console\InstallCommand::class,
Console\ClientCommand::class,
Console\KeysCommand::class,
]);
...
}
to make it work with general artisan command, we can register these commands ourselves. somewhere within the boot method of AuthServiceProvider maybe.
public function boot() {
$this->commands([
Console\InstallCommand::class,
Console\ClientCommand::class,
Console\KeysCommand::class,
]);
}
Now we can call Artisan::call('passport:install') or the other 2 commands.
From Laravel Docs
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});
Import this line on top.
use Illuminate\Support\Facades\Artisan;
And Enter line below for command
Artisan::call('passport:client --password')

Categories