creating a folder once user registred laravel 5 - laravel-5

I would like to create a folder inside Storage folder in Laravel 5, once you register and pick your username, a folder with that user will be created for you.
If you created user : john5500 a folder inside Storage will be created with 'john5500' and will belong only to that user.

Mark, see the code below.
This code I use to create a new user in my database.
Information about ManagementCreateRequest $Request can be found via this URL.
Laravel Controller Validation
In short I'm validating my input via Controller Validation in Laravel.
After the validation passes I get all the data from the validation in the variable $Request.
After that I create the user as below. After creating the user I send a redirect to the management page. This page contains an overview of all the users in the database.
public function store(ManagementCreateRequest $Request)
{
// Create user
Management::create($Request->all());
// Return view
return redirect('management')
->with('Success', 'User created.');
}
If I would to create a directory I would do it like this.
public function store(ManagementCreateRequest $Request)
{
// Create user
Management::create($Request->all());
// Create directory
File::MakeDirectory('/path/to/directory' . $Request->username);
// Return view
return redirect('management')
->with('Success', 'User created.');
}
Replace /path/to/directory with the actual path to your storage directory.
For example: Under CentOS my storage directory would be.
/var/www/Site Name/storage
Don't forget to replace 'Site Name' with the name of your Laravel site.
More detailed information about File:makeDirectory can be found via this link:
Laravel Creating Directory

Lravel 5 comes with an excellent filesystem. You could simply do:
Storage::makeDirectory($directory);
See the documentation for more details: http://laravel.com/docs/5.0/filesystem#basic-usage

You can use Laravel File Facade:
File::makeDirectory($path, $mode = 0755, $recursive = false, $force = false);
Ensure storage is writable
public function create(array $data)
{
//return
$user = User::create([
'name' => $data['name'],
'username'=>$data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
\File::makeDirectory(storage_path($data['username']));
return $user;
}

Related

Updating user profile image along with user profile in Laravel

// Creating account
public function store()
{
$this->validate(request(),[
all inputs validated...
including ‘photo’ => ‘file|image|max:500’
]);
if(request()->hasFile(‘photo’)){
$path = request()->file(‘photo’)->store(‘profile’, ‘public’);
}
else{
$path = ‘avatar.jpg’;
}
$user = User::create(
[
// all inputs requested...
including ‘photo’ => $path,
]);
// I log user in and redirect to intended destination
// Success...was able to output profile photo and other things
}
// Now Update account is my problem
public function update(Request $request, User $user-profile)
{
$this->validate($request, [
all inputs validated..
including ‘photo’ => ‘file|image|max:1500
]);
// Genesis of my problem
if (request()->hasFile(‘photo’)){
$path = request()->file(‘photo’)->store(‘profile’, ‘public’);
}
else{
// Please what should I do here....
$user-profile->update(
[
// all inputs requested...
including ‘photo’ => ???
]);
}
The “else” condition of the update method is where my problem lies. Reason: if a user already has a profile photo, if I do the same “else” as during account creation, the ‘avatar.jpg’ then overwrites their initial photo which is not right. Please what can I do to solve this? So when user registers with photo, it’s loaded else avatar is loaded. But when user updates, what do I do? Thanks in advance.
Do same like as store :
if (request()->hasFile(‘photo’)){
$path = request()->file(‘photo’)->store(‘profile’, ‘public’);
} else {
$path = ‘avatar.jpg’;
}
i dont think you need the else.. if user has uploaded photo then you will need to overwrite users path in the db (which you are doing in the if) otherwise you dont need to and the save() call shouldnt even touch the path field in db
i am assuming your code for creation isnt being triggered somehow when you do the update.

update profile in laravel API for mobile apps

I want to build an api for mobile apps. for now, i want to create an edit profile api. but i dont know how to store an image, if user wants to upload their avatar.
Here is my code:
public function profileedit($id, Request $request){
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar;
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>$users->thumbnail,
'status'=>200,
];
return response()->json($data);
}
how to put the $request->avatar into my project storage, and show it in url form (my project is already uploaded on the server)
The easiest way to store files in Laravel is this.
use Illuminate\Support\Facades\Storage;
public function profileedit($id, Request $request){
//validator place
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar->store('avatars','public');
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>Storage::url($users->thumbnail),
'status'=>200,
];
return response()->json($data);
}
but as you probably know, you should run php artisan storage:link command to generate storage shortcut in public directory.
for security reason you can use validator to let only image file store. in this example I limited file to all image types with maximum 4MB size
$request->validate([
'avatar' => 'required|image|max:4096',
]);
for more information these are document links.
File Storage
Validation

Can not pass variable to Config::set in laravel elfinder

I am using laravel 5.5 with backpack as admin panel and i making a project for listing Departments and their Clients and i want to use elfinder to connect to each client folder when i edit the client , So i created a middleware for elfinder to create the client folder and to change the elfinder.dir to that directory the first part of creating dir is done but the problem is in Config::set is not working ,My Code is:
The Middleware :
public function handle($request, Closure $next)
{
$iid = $request->route('client');
if (!Storage::disk('doc')->exists('$iid')){
Storage::disk('doc')->makeDirectory($iid);
}
\Config::set('elfinder.dir', $iid);
return $next($request);
}
The Route:
Route::get('admin/client/{client}/edit', 'Admin\ClientCrudController#edit')->middleware('elfindernew');
The ElfinderController :
public function showConnector()
{
$roots = $this->app->config->get('elfinder.roots', []);
if (empty($roots)) {
$dirs = (array) $this->app['config']->get('elfinder.dir', []);
foreach ($dirs as $dir) {
$roots[] = [
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => storage_path('doc')."/".$dir,
'URL' => url($dir), // URL to files (REQUIRED)
'accessControl' => $this->app->config->get('elfinder.access') // filter callback (OPTIONAL)
];
}
I don't Know what is wrong Can someone Help me.....
You have to do it like this:
config(['elfinder.dir', $iid]);

Laravel password recovery template

I have the following code which sends a passowrds recovery mail:
public function recovery(Request $request)
{
$validator = Validator::make($request->only('email'), [
'email' => 'required'
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject(Config::get('boilerplate.recovery_email_subject'));
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->response->noContent();
case Password::INVALID_USER:
return $this->response->errorNotFound();
}
}
Which I found out uses the following template: resources/views/auth/emails/password.php
which is an empty file.
How I can access the token from this template?
Isn't there any built-in view to use from laravel?
The function in your questions doesn't return a view.
Also, I'm unfamiliar with that path to the view that is in your question. Which version of Laravel are you using?
Anyhow, you can get the reset token from the DB, just like any other value in the DB. E.g. from a controller that is returning a view:
$user = User::find(Auth::id());
$remeber_token = $user->remember_token;
return view('to_your_view.blade.php', compact('remember_token');
And then in the view file:
{{ $remember_token }}
This will output it, no need to use echo or anything.
But, again, the function you pasted into your question is not a function that is returning a view, so I'm not sure where to tell you to put the above code.
As for your questoin about Laravel having an in-built view for 'this', in Laravel 5.3, at least, the view I assume you want will be within `resources/views/auth/passwords/'.

Attach authenticated user to create

I'm trying to attach the currently logged in user to this request, so that I can save it in the database. Can someone point me in the right direction, please?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So, I have come up with the following using array_merge, but there must be a better way, surely?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = array('created_by' => Auth::user()->id, 'modified_by' => Auth::user()->id);
$merged_array = array_merge($input, $userDetails);
$leadStatus = $this->leadStatusRepository->create($merged_array);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So you can use Auth Facade to get information of currently logged user.
For Laravel 5 - 5.1
\Auth::user() \\It will give you nice json of current authenticated user
For Laravel 5.2 to latest
\Auth::guard('guard_name')->user() \\Result is same
In laravel 5.2, there is new feature called Multi-Authentication which can help you to use multiple tables for multiple authentication out of the box that is why the guard('guard_name') function is use to get authenticated user.
This is the best approach to handle these type of scenario instead of attaching or joining.
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = \Auth::user(); //Or \Auth::guard('guard_name')->user()
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
Hope this helps.

Resources