Laravel: Save css file from database data - laravel

On the Admin interface I saved the contents of the editor into a database, several css can be created and their order can be changed.
Database table:
id (bigint) | name (varchar) | content (longtext)
This not work:
Storage::disk('local')->append('storage/css/custom.css', $request->input('content'));
When editing, how can I generate the content created in the database and save it to a css file?
update: The backup was resolved but how can I retrieve only the data in the css file from the database is placed before each table: {"content:" ...}?
private function saveToFile()
{
$cssmerge = Css::all('content');
Storage::disk('public')->put('css/custom.css', $cssmerge);
}
Thanks!
CssController.php:
public function store(Request $request)
{
$csscontent = $request->all();
// Create css style
$csscontent = new Css;
$csscontent->name = $request->input('name');
$csscontent->content = $request->input('content');
$csscontent->save();
return redirect('backend/css')->withSuccessMessage( __('Successfully created!'));
}
public function update(Request $request, $id)
{
// Update css
Storage::disk('local')->append('storage/css/custom.css', $request->input('content'));
$csscontent = Css::findOrFail($id);
$csscontent->name = $request->input('name');
$csscontent->content = $request->input('content');
$csscontent->save();
switch($request->input('save-form')) {
case 'save-btn-redirect':
return redirect('backend/css')->withSuccessMessage( __('Successfully modified!'));
break;
case 'save-btn':
return back()->withSuccessMessage( __('Successfully modified!'));
break;
}
return view('backend.css.index', compact('csscontent'));
}

Related

Laravel Multiple Edit/Upload File

I want to make my code more efficient in my Controller. This code is about to update file in the database and then delete the file were chosen, rather than use if-condition i will use switch statement and then call the updateFile function for each case of file name. But i have problem on my switch statement, it supposed to run for each case but doesn't.
private function updateFile($strFileName, $oldFileName){
if($request->file($strFileName)){
if($request->$oldFIleName){
Storage::delete($request->$oldFIleName);
}
$validatedData[$strFileName] = $request->file($strFileName)->store('post-files');
}
}
public function update(Request $request, Task $task)
{
//storing files request
$rules = [
'file_jamlak' => 'mimes:pdf,png,jpg|file|max:4096',
'file_kontrak' => 'mimes:pdf,png,jpg|file|max:4096',
'file_jamuk' => 'mimes:pdf,png,jpg|file|max:4096']
//validate rules in to new variable
$validatedData = $request->validate($rules);
//the switch
$file_name = $request->file();
switch($file_name){
case 'file_jamlak' : $this->updateFile('file_jamlak', 'oldJamlak');
}
//condition
//jamlak
if($request->file('file_jamlak')){
if($request->oldJamlak){
Storage::delete($request->oldJamlak);
// return $request->oldJamlak;
}
$validatedData['file_jamlak'] = $request->file('file_jamlak')->store('post-files');
$validatedData['jamlak'] = 1;
}
//kontrak
if($request->file('file_kontrak')){
if($request->oldKontrak){
Storage::delete($request->oldKontrak);
}
$validatedData['file_kontrak'] = $request->file('file_kontrak')->store('post-files');
$validatedData['kontrak'] = 1;
}
//add user id
$validatedData['user_id'] = auth()->user()->id;
//update eloquent
Task::where('id', $task->id)
->update($validatedData);
//dd($file_name);
return redirect('/admin/tasks')->with('success', 'New post has been updated!');
}
i think i made mistake on the $file_name, that it supposed to store file name but doesn't work. Please help me
Make sure you've file name in your case which you are checking against:
// ...
//the switch
$file_name = $request->file();
switch($file_name){
// make sure this name matches the name of the file you are submitting
// from the form on front end to be able to fall into this case
case 'file_jamlak' : $this->updateFile('file_jamlak', 'oldJamlak');
// ...

How to save data on different database tables in Laravel Backpack

how to save the data from the Features fields on a different table. Example in the link below, it is saving the Features table fields in a JSON field in the database. However, I want to save this data from the features into another table.
https://demo.backpackforelavel.com/admin/product/211/Edit
I'm coming back here to post my answer. I managed to settle, I'm putting here to help other developers.
This first part of the question I have already solved. But now I can not bring the data from the Features fields in the form.
Below is the source code that I was able to save and edit the form data. However, I can not carry the data from the Feature fields. Someone knows how I can carry the field data in Feature
class ProductCrudController extends CrudController
{
use ListOperation;
use CreateOperation {
store as traitStore;
}
use UpdateOperation {
update as traitUpdate;
}
use DeleteOperation;
public function store()
{
// insert item in the db
$item = $this->crud->create($this->crud->getRequest()->except(['save_action', '_token', '_method']));
$features = json_decode($this->crud->getRequest()->input('features'));
foreach ($features as $itens) {
$obj = new Feature();
$obj->product_id = $item->getKey();
$obj->name = $itens->name;
$obj->save();
}
// show a success message
\Alert::success(trans('backpack::crud.insert_success'))->flash();
return redirect('admin/product');
}
public function update()
{
$featureForm = json_decode($this->crud->getRequest()->input('features'));
// insert item in the db
$item = $this->crud->update($this->crud->getRequest()->id, $this->crud->getRequest()->except(['save_action', '_token', '_method', 'features']));
$objF = Feature::where('product_id', $item->getKey())->get();
foreach ($objF as $itens) {
Feature::where('id', $itens->id)->delete();
}
foreach ($featureForm as $itens) {
$obj = new Feature;
$obj->product_id = $item->getKey();
$obj->name = $itens->name;
$obj->save();
}
// show a success message
\Alert::success(trans('backpack::crud.insert_success'))->flash();
return redirect('admin/product');
}
}
I'm coming back here to post my answer. I managed to settle, I'm putting here to help other developers.
I was able to bring the data in the form edition, in the Features fields. I used the Mutators in the Model - https://laravel.com/docs/8.x/eloquent-mutators
Below is the example I did.
It would be interesting to have an example of this in the official documentation or demo project. I believe it would help a lot also to other developers.
//model Product
public function getFeaturesAttribute($value)
{
$objects = Features::where('product_id', $this->id)->get();
$array = [];
foreach ($objects as $itens) {
$obj = new stdClass;
$obj->name = $itens->name;
$array[] = $obj;
}
return \json_encode($array);
}
There are a few ways to go about it. Personally I prefer to create accessors and mutators in the model - https://laravel.com/docs/8.x/eloquent-mutators . Not only does it keep the CrudController clean (so updateable) but it also allows you to save/load stuff from other forms (ex: user-facing forms).
//model Product
public function getFeaturesAttribute($value)
{
$objects = Features::where('product_id', $this->id)->get();
$array = [];
foreach ($objects as $itens) {
$obj = new stdClass;
$obj->name = $itens->name;
$array[] = $obj;
}
return json_encode($array);
}

Rename file in Laravel 5.3

I want to rename existing files in Laravel .. like I have items table and every item has picture .. and when I rename the item I mean update the item ..
I want to rename the image as well ..
This is my code ..
public function update(Request $request, $id)
{
$color = Color::find($id);
$old_value = $color->color_name;
if($request->ajax())
{
$check = Color::where('color_name','=',$request->color_name)->count();
if($check == 1 and $request->color_name <> $old_value)
{
return response()->json([
'error'=>'same',
'old_value'=>$old_value,
]);
}
else
{
$color->color_name = $request->color_name;
$color->save();
$file = base_path()."/public/upload/colors/1/$old_value.jpg";
/* here where i want to rename the variabel file to the new name com from the request */
}
}
}
Check out the Official Documentation for your needs
Storage::move('old/file1.jpg', 'new/file1.jpg');
I think you might be able to change the file name when you use move method
Filesystem/Cloud Storage

Laravel - Best way to store user and his/her dynamically created relations on submit

Which way should I store User Relations which are made "Dynamically"?
By that i mean. I have People table with record of husband for example now husband can add as relation to him (hasMany) his wife and children. Now I have setup the model and it works
Model
This relations are in same table as data is same for them I only need to know if they belong to husband
public function children(){
return $this->hasMany( get_class($this) ,'people_id','id');
}
public function parent(){
return $this->belongsTo( get_class($this) , 'people_id','id');
}
Now when i go to form and add a person husband there. I would have an option to dynamically add his children() (his wife, his children, his grandma...) and submit once its done.
Now i have tought about saving these children to Session first (put them in array) and on submit to post it to controller. Is this a good way or should i do it some other way?
(I hope i explained this well, if not i will try to explain it better)
I have done it like this i dont know if this way is ok but it works for me. Also to add i have just used name for the DB data as i wanted to get this to work.
Store parent and his/her children (if any) in DB from Session
public function store(AdminCreatePersonRequest $request)
{
$data = $request->all();
$parent = new Person;
$parent->name = $data['name'];
$parent->save();
$children = $request->session()->pull('children');
if ($children != null) {
foreach($children as $childData){
$child = new Person(['name' => $childData['child-name']]);
$parent->children()->save($child);
}
}
return redirect('dashboard')->with('success', ['The user was successfully created']);
}
AJAX
Add child to session
public function add(AdminCreatePersonChildRequest $request)
{
$temp = $request->session()->get('children',[]);
$data = $request->all();
unset($data['_token']);
array_push($temp,$data);
end($temp);
$key = key($temp);
$data += ['id' => $key];
$request->session()->put('children', $temp);
return $data;
}
Remove child from session
public function delete(Request $request, $id) {
$temp = $request->session()->pull('children');
unset($temp[$id]);
$request->session()->put('children', $temp);
return 1;
}
Load children from Session on view create (if any)
public function load(Request $request) //get children from session (if exists)
{
$data = $request->session()->get('children');
if($data != null){
return $data;
}
else {
return 0;
}
}
Clear all children from session
public function clear(Request $request) //remove children from session
{
$request->session()->forget('children');
return 1;
}
And with data form controller you update your view (in my case add <li> to <ul> element)

Laravel profile edit

Alright , I have used this way to save the users info and It works perfect,
static public function memberSave($request) {
$signup = false;
$member = new Members();
$member->name = $request['name'];
$member->email = $request['email'];
$member->password = bcrypt($request['password']);
$member->save();
if (!empty($member->id)) {
$new_id = $member->id;
DB::insert("INSERT INTO roles VALUES ($new_id, 5613)");
$signup = true;
Session::flash('sm', 'Thank you! You have signed up successfully!');
}
return $signup;
}
but when making this for editing the profile(by user) It doesn't work
becuase I use new(); (making object)
I also didn't succeed to use find(); so I tried to use this
static public function saveProfile($id,$name,$email,$password) {
$sql = "UPDATE members SET name=?,email=?,password=? WHERE id=?";
$member = DB::select($sql, [$name,$email,$password,$id]);
but when I want to bcrypt the password in laravel doesnt work .
this is the code also in the second page
public function postProfile(ProfileValidation $request) {
if (Members::saveProfile($request['id'], $request['name'], $request['email'], $request['password'])) {
return redirect('');
}
}
I hope getting helped for editing the users profile by laravel , thanks.
Your Members class must extend Eloquent\Model for following this code to work.
class Members extends Model {
// optional
protected $table = 'members';
...
To find and update the member using email,
// find the single member
$member = Members::where('email', request['email'])->first();
// update the member
$member->name = $request['name'];
$member->password = $request['password'];
// now save the updated member
$member->save();
In order to to encrypt Password, Laravel provides Hash Facade,
// import this
use Hash;
...
// encrypt Password
$encrypted = Hash::make($request['password']);
...
if you want your user automatically hash the password at your model put:
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
and you can directly check for the user if exist create new or update it:
public function saveMember($request)
{
$member = Member::findOrNew($request->email);
//All your input you want to save
$member->save();
}

Resources