online software programming courses

What is difference between store() and storeAs() function in Laravel?

We will learn

1. What is store function in Laravel?

2. What is storeAs function in Laravel?

3. Difference between store and storeAs function in Laravel

4. When to use them?

1. What is store function in Laravel?

If you have a file object(it could be a file or image object) in your controller, then you will have store() method associated with it. This particular store function is used to save file or image objects in your server. This store method creates an unique ID for the file and uses this ID as the file or image name. This unique ID is generated by Laravel.

$path = $request->file(‘avatar’)->store($path, $options);
//$path =j37902kjsaj23834ksjhsoshs94048720.jpg

As you can see, there is no name option in the store method. The first parameter is the path where you want to save the object, and the second one is the type of location, like public or private folder.

2. What is storeAs function in Laravel?

This function is the same as the above mentioned function store. The only difference is that it takes a user-generated name when the file is saved on a server.

$name = “myphotoname.jpg”;
$path = $request->file(‘avatar’)->storeAs($path, $name, $options);

As you can see, you can send a user-generated name in the storeAs function, which you can not do with store. And another difference is that storeAs function takes three parameters. First parameter is the path where you want to save the file, the second one is the name, and the third one is what type of location, like public or private folder. So in our case, we are using the public folder as an application(like a website or an app) would access from a web browser.

3. Difference between store and storeAs function in Laravel

The difference is that store method takes two parameters and creates unique id for storing image while storeAs method takes three parameters and takes a user-generated name for storing image. Both of them save images in public folder under

/storage/app/public

4. When to use them?

If you want your images to be publicly accessible then use any of them. When you just want unique id created for you automatically, then use store method. If you want to assign a name by yourself then use storeAs.