// 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.
Related
i had some problem for updating my data, i was able to catch the file that was going to be updated by using dd and they are there, but when i was submitting the form the data remains the same, nothing change and no error whatsoever, here are my store(update) controller :
public function store(Request $request)
{
//dd($request);
$request->validate([
'attachment_name' => 'required|file|image|mimes:jpeg,png,jpg,gif,svg|max:10048',
]);
$storedImage = $request->attachment_name->store('public/image/');
MediaOrder::updateOrCreate(['id' => $request->id],
[
'nomor'=> $request->nomor,
'nomor_reference'=> $request->nomor_reference,
'periode_start'=> $request->periode_start,
'periode_end'=> $request->periode_end,
'category_id'=> $request->category_id,
'type_id'=> $request->type_id,
'agency_code'=> $request->agency_code,
'agency_name'=> $request->agency_name,
'advertiser_code'=> $request->advertiser_code,
'advertiser_name'=> $request->advertiser_name,
'brand_code'=> $request->brand_code,
'brand_name'=> $request->brand_name,
'nett_budget'=> $request->nett_budget,
'gross_value'=> $request->gross_value,
'nett_cashback'=> $request->nett_cashback,
'nett_bundling'=> $request->nett_bundling,
'version_code'=> $request->version_code,
'spot'=> $request->spot,
'accountexecutive_name'=> $request->accountexecutive_name,
'group_id'=> $request->group_id,
'userto_name'=> $request->userto_name,
'notes'=> $request->notes,
'attachment_name'=> $storedImage,
]);
flash_success_store('Media Order successfully updated.');
if ($request->ajax()) {
return redirect_ajax_notification('media-order.index');
} else {
return redirect_ajax('media-order.index');
}
}
i already find and change it myself but to no avail, maybe someone can have a solution?, thank you for your time.
The most common reason that the model is not updated or entered is that you do not make the attributes fillable in the model itself. Go to your model MediaOrder and check if you have set all attributes fillable.
protected $fillable = [..];
Before anything, thank you for your help
I've been having a problem for days with Laravel login. My only credential to login users is their document (it's quite a small system) but, recently, I'm starting to have trouble when logging in with documents larger than 10 chars. Whenever I try to log in with a document like that, it sends me back to the login view with no errors, it just doesn't let me log in.
I'm using the Auth::loginUsingId($request->document) (I already checked that the user had $primaryKey = 'document')
I tried to refresh all migrations, show the output of every single line in the login method, but everything seems to be fine, the Auth::loginUsingId() returns the corresponding User instance but it's just not redirecting to the right view. I really hope you can help me with this one
Here is the code of my login method in the AdminController.php
public function login(Request $request) {
// validacion
$rules = [
'document' => 'required|numeric|exists:users,document'
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
// login
$document = $request->document;
if(Auth::loginUsingId($document)){
return redirect()->route('home');
}else{
return redirect()
->route('admin.login')
->with('status', 'Login Failed');
}
}
Hello stackoverflow geeks, I'm in my final stages of the laravel learning curve all thanks to you guys.
However, i need to generate a warning message like "You cannot delete a role assigned to a user" every time a user tries to delete a role assigned to a user.
instead it loads a page with an sql error. how to i do it?
And how do i avoid a password that has been already been stored from being hashed again. eg:- $2y$10$p8JwI5P4yE2UFo2.vHP99.0dP2jU7ll/9w73IzUa9/yegKOSTHJWq is always hashed every time i edit a user's information.
Thanks you all who've made learning laravel easy for me by answering in time
code
public function destroy(Request $request,$id)
{
// delete
// $role = Role::find($id);
//$role->delete();
$role = Role::find ($id);
if ($role->users() !=null) {
return redirect()->back()->withInput(['warning' => 'Not allowed']);
}
$role->delete();
// redirect
Session::flash('message', 'Record successfully deleted!');
Session::flash('alert-type', 'success');
return Redirect::to('role');
}
This highly depends on how you want to handle the errors. You can either catch the sql exception and display your custom error OR what is probably better for you is to handle the incoming request, validate it and return an error if validation fails.
Here are the validation docs : https://laravel.com/docs/5.3/validation
You have multiple options on how to validate a request. Simple example to validate a title is unique in the table posts and is maximum 255 chars long:
$this->validate($request, [
'title' => 'required|unique:posts|max:255'
]);
If you cannot find a rule that is helping you simply define your own validation rule https://laravel.com/docs/5.3/validation#custom-validation-rules
Ofcourse you can also do the validation manually. In your request or in your controller (depends on your setup) just check for it
// assuming you want to delete an entry
public function delete(Request $request, $id)
{
$role = App\Role::findOrFail($id);
if ($role->users() != null) {
return redirect()->back()->withInput(['message' => 'Not allowed']);
// now you can output $message
}
$role->delete();
return ...
}
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.
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;
}