LadyDeathKZN

LadyDeathKZN

Member Since 10 Months Ago

Experience Points
2,320
Total
Experience

2,680 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
2
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
2,320 XP
Nov
20
1 day ago
Activity icon

Replied to Can't Delete Image / File From Public Folder

Post may be old but has saved me 3 hours of frustration. Thank YOU!

Nov
11
1 week ago
Activity icon

Replied to Real Time Notifications

Hi,

I am not good with pusher, though I can recommend that you use websockets, it is completely free and easy to implement since you already have pusher in your project, I hope someone can help you out: https://www.youtube.com/watch?v=wknGvg0sTAc

Oct
30
3 weeks ago
Activity icon

Replied to JSON Data To Another Domain

Hi, thank you so much for the advice, API completely got forgotten! Thank you!!!

Oct
29
3 weeks ago
Activity icon

Started a new Conversation JSON Data To Another Domain

Hi, I was wondering if there was an easier way to send form info from one domain to another. Both are Laravel projects. I don't want to connect both databases on both projects. Is there a way to send the form info as JSON to a route on another domain?

Or is there another way to send form data to another domain without connecting both databases?

Oct
11
1 month ago
Oct
02
1 month ago
Activity icon

Replied to Check Permission And User_id From Pivot Table Globally

Sadly this isn't going to work for what I need. I just need to hide the buttons stopping them from Editing, Creating, or Deleting. Though the gates will come in handy sometime later

Sep
26
1 month ago
Activity icon

Replied to Check Permission And User_id From Pivot Table Globally

Thank you so much :). Will check it out!

Sep
25
1 month ago
Activity icon

Started a new Conversation Check Permission And User_id From Pivot Table Globally

Hi, I have been looking up ways to check a permission globally. The permission is in a pivot table with the user_id. I will be using the Auth::user()->id to see if the user that is logged in is the same as the one on the pivot table.

How can I globally check the permission_id in the entire laravel project without having to add it to each view? Also can one make a middleware for this instead?

Sep
20
2 months ago
Activity icon

Replied to Save User_id And Permission_id To Pivot

The problem is it can't be nullabel I need that user_id in there otherwise the permissions function won't work like expected

Activity icon

Replied to Save User_id And Permission_id To Pivot

I am getting a user_id cannot be null or even permissions() call member null

Sep
19
2 months ago
Activity icon

Replied to Save User_id And Permission_id To Pivot

Thank you kindly for explaining, I will try it out :)

Activity icon

Started a new Conversation Save User_id And Permission_id To Pivot

Hi,

I have a modal that has a multiple selection for permissions; and a hidden field with that users_id. I want to store the user_id and the permission_id in the pivot table. PermissionController

<?php

namespace App\Http\Controllers;

use App\Permission;
use App\User;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class PermissionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $permissions = Permission::all();
        return view ('admin.permissions.index', compact('permissions'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $users = User::all();
        $permissions = Permission::all();
        return view('admin.permissions.assign', [
            'users' => $users,
            'permissions' => $permissions
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $permissions_id = Input::get('permissions');
        $permission->users()->sync($permissions_id);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Permission  $permission
     * @return \Illuminate\Http\Response
     */
    public function show(Permission $permission)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Permission  $permission
     * @return \Illuminate\Http\Response
     */
    public function edit(Permission $permission)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Permission  $permission
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Permission $permission)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Permission  $permission
     * @return \Illuminate\Http\Response
     */
    public function destroy(Permission $permission)
    {
        //
    }

    public function status($id) {
        $permission = Permission::find($id);
        if($permission->status == 'enabled') {
            $permission->status = 'disabled';
            $permission->save();
            return redirect()->back()->with('error','Permission disabled successfully');
        } else {
            $permission->status = 'enabled';
            $permission->save();
            return redirect()->back()->with('success','Permission enabled successfully');
        }

    }
}

assign.blade.php

@extends('layouts.app')

@section('content')

<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
  <h1 class="h3 mb-0 text-gray-800">Users</h1>
</div>

<!-- Content Row -->
<div class="row">
  <div class="col-md-12 col-xs-12 col-lg-12">
    <div class="card shadow mb-4">
      <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Users</h6>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
            <thead>
              <tr>
                <th>User</th>
                <th>Email</th>
                <th>Role</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tfoot>
              <tr>
                <th>User</th>
                <th>Email</th>
                <th>Role</th>
                <th>Actions</th>
              </tr>
            </tfoot>
            <tbody>
              @foreach($users as $user)
              <tr>
                  <td>{{$user->name}}</td>
                  <td>{{$user->email}}</td>
                  <td>{{ucfirst($user->roles->role)}}</td>
                  <td>
                      <a href="#" data-toggle="modal" data-target="#assignModal{{$user->id}}" class="mr-1 btn btn-circle btn-sm btn-dark"><i class="fas fa-user-check"></i></a>
                  </td>
              </tr>

              <!-- Assign Modal-->
              <div class="modal fade" id="assignModal{{$user->id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                    <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Assign Permissions</h5>
                        <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                        </div>
                        <div class="modal-body">
                            <form action="{{route('permissions.store', $user->id)}}" method="post">
                            @csrf
                            <div class="row">
                                <label for="permissions">Assign</label>
                                <br>
                                <select class="js-tags form-control" name="permissions[]" multiple="multiple" style="width: 100% !important">
                                    @foreach($permissions as $permission)
                                        @if($user->roles->id == $permission->role_id)
                                            <option value="{{$permission->id}}">{{ucwords($permission->permission)}}</option>
                                        @endif
                                    @endforeach
                                </select>
                                <input type="hidden" value="{{$user->id}}">
                            </div>
                            <div class="modal-footer">
                                <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                                <button class="btn btn-primary" type="submit">Assign</button>
                            </div>
                            </form>
                        </div>
                    </div>
                    </div>
                </div>

              @endforeach
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

@endsection

Models

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    //

    public function roles()
    {
        return $this->belongsTo('App\Role', 'role_id');
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'permission_user');
    }
}

User Model:
public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'permission_user');
    }

Role Model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    //Allow Role for User
    public function user()
    {
        return $this->belongsTo('App\User', 'role_id');
    }

    public function permissions()
    {
        return $this->belongsTo('App\Permission', 'role_id');
    }

}

How can I save the user_id and permission_id in the pivot?

Sep
12
2 months ago
Activity icon

Replied to Duplicate Info To Another Row In DB Once Saved

How does one go about doing that? Have never done that before :). Would this work on the update function too?

Activity icon

Replied to Duplicate Info To Another Row In DB Once Saved

Got it sorted like so, however I am curious - is there any other way to do this? Instead of using repetitive code

public function store(Request $request)
    {
        $form = new Form;
        $form->job_description = "JOB-" . date('dMy-Hi');
        $form->start_date = $request->start_date;
        $form->end_date = $request->end_date;
        $form->event = $request->event_form;
        $form->editing = $request->editing_form;
        $form->additional_instructions = $request->additional_instructions;
        $form->company_id = $request->company;
        $form->brand_id = $request->brand;
        $form->type_coms = $request->type_communication;
        $form->frequency = $request->frequencies;
        $form->media_types = $request->media_types;
        $form->client_id = Auth::user()->id;

        //VersionControl
        $version = new FormVersionControl;
        $version->job_description = "JOB-" . date('dMy-Hi');
        $version->start_date = $request->start_date;
        $version->end_date = $request->end_date;
        $version->event = $request->event_form;
        $version->editing = $request->editing_form;
        $version->additional_instructions = $request->additional_instructions;
        $version->company_id = $request->company;
        $version->brand_id = $request->brand;
        $version->type_coms = $request->type_communication;
        $version->frequency = $request->frequencies;
        $version->media_types = $request->media_types;
        $version->client_id = Auth::user()->id;

        $form->save();

        if ($form->save()) {
            $channel_ids = Input::get('channels');
            $form->channels()->sync($channel_ids);
        }

        if ($form->save()) {
            $clientuser = Auth::user()->id;
            $form->clientlog()->sync($clientuser);
        }

        return redirect(route('client-upload.create', $form->id))->with('success', 'Form added successfully, please upload media');

    }
Activity icon

Started a new Conversation Duplicate Info To Another Row In DB Once Saved

Hi, I'm trying to make a version control, where a user saves the form info and can view the changes made to it later. Almost like what WordPress does.

I have tried the duplicate() in my controller but it does not work. my store controller for the form:

public function store(Request $request)
    {
        $form = new Form;
        $form->job_description = "JOB-" . date('dMy-Hi');
        $form->start_date = $request->start_date;
        $form->end_date = $request->end_date;
        $form->event = $request->event_form;
        $form->editing = $request->editing_form;
        $form->additional_instructions = $request->additional_instructions;

        $form->company_id = $request->company;
        $form->brand_id = $request->brand;
        $form->type_coms = $request->type_communication;
        $form->frequency = $request->frequencies;
        $form->media_types = $request->media_types;
        $form->client_id = Auth::user()->id;

        $form->save();

        if ($form->save()) {
            $channel_ids = Input::get('channels');
            $form->channels()->sync($channel_ids);
        }

        if ($form->save()) {
            $clientuser = Auth::user()->id;
            $form->clientlog()->sync($clientuser);
        }

        //Version Control


        return redirect(route('client-upload.create', $form->id))->with('success', 'Form added successfully, please upload media');

    }

I have a model and controller for FormVersionControl. I also tried making a new FormVersionControl which also resulted in errors. Who can I go about this that once it is saved it duplicates that forms info in the version-control row in the database?

Sep
02
2 months ago
Activity icon

Replied to Route ID To Database Via Controller

<?php

namespace App\Http\Controllers;

use App\ClientUpload;
use App\ClientFormFile;
use App\Form;
use Storage;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;

class ClientUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $forms = Form::all();
        return view('uploads.client.index',
        ['forms'=>$forms]
        );
    }

    public function create($id)
    {
        $form = Form::find($id);
        return view('uploads.client.create', [
            'form' => $form
        ]);
    }

    /**
     * Handles the file upload
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws UploadMissingFileException
     * @throws \Pion\Laravel\ChunkUpload\Exceptions\UploadFailedException
     */
    public function upload(Request $request, $form_id) {
        // create the file receiver
        $receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
        // check if the upload is success, throw exception or return response you need
        if ($receiver->isUploaded() === false) {
            throw new UploadMissingFileException();
        }
        // receive the file
        $save = $receiver->receive();
        // check if the upload has finished (in chunk mode it will send smaller files)
        if ($save->isFinished()) {
            // save the file and return any response you need, current example uses `move` function. If you are
            // not using move, you need to manually delete the file by unlink($save->getFile()->getPathname())

            return $this->saveFile($save->getFile(), $form_id);
        }
        // we are in chunk mode, lets send the current progress
        /** @var AbstractHandler $handler */
        $handler = $save->handler();
        return response()->json([
            "done" => $handler->getPercentageDone(),
            'status' => true
        ]);
    }

    /**
     * Saves the file
     *
     * @param UploadedFile $file
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function saveFile(UploadedFile $file, $form_id)
    {
        $fileName = $this->createFilename($file);
        $fileAuth = Auth::user()->name;
        // Build the file path
        $filePath = "upload/client/".$fileAuth;
        $finalPath = storage_path("app/".$filePath);
        // Move the file name
        $file->move($finalPath, $fileName);
        // Save to Database
        $file = new ClientFormFile;
        $file->filepath = storage_path("app/".$filePath).'/'.$fileName;
        $file->user_id = Auth::user()->id;
        $file->form_id = $form_id;
        $file->save();
        return response()->json([
            'path' => $filePath,
            'name' => $fileName
        ]);
    }
    /**
     * Create unique filename for uploaded file
     * @param UploadedFile $file
     * @return string
     */
    protected function createFilename(UploadedFile $file)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = str_replace(".".$extension, "", $file->getClientOriginalName()); // Filename without extension
        // Filename with extension
        $filename .= "." . $extension;
        return $filename;
    }

}

For anyone else in the future

Activity icon

Replied to Que A Artisan Command

I have looked at schedueliing and cron jobs, though the system won't need to be backuped up so often and would like to give the user the option to do so when necessary

Activity icon

Replied to Route ID To Database Via Controller

It actually uses both controller and the javascript component with the route

Activity icon

Replied to Route ID To Database Via Controller

It is done via a JavaScript component:

//Resumable
var $ = window.$; // use the global jQuery instance

var $fileUpload = $('#resumable-browse');
var $fileUploadDrop = $('#resumable-drop');
var $uploadList = $("#file-upload-list");

if ($fileUpload.length > 0 && $fileUploadDrop.length > 0) {
    var resumable = new Resumable({
        // Use chunk size that is smaller than your maximum limit due a resumable issue
        // https://github.com/23/resumable.js/issues/51
        chunkSize: 5 * 5028 * 5028, // 1MB
        simultaneousUploads: 5,
        testChunks: false,
        throttleProgressCallbacks: 1,
        maxFiles: 1,
        // Get the url from data-url tag
        target: $fileUpload.data('url'),
        // Append token to the request - required for web routes
        query:{_token : $('input[name=_token]').val()},

    });

// Resumable.js isn't supported, fall back on a different method
    if (!resumable.support) {
        $('#resumable-error').show();
    } else {
        // Show a place for dropping/selecting files
        $fileUploadDrop.show();
        resumable.assignDrop($fileUpload[0]);
        resumable.assignBrowse($fileUploadDrop[0]);

        // Handle file add event
        resumable.on('fileAdded', function (file) {
            // Show progress bar
            $uploadList.show();
            // Show pause, hide resume
            $('.resumable-progress .progress-resume-link').hide();
            $('.resumable-progress .progress-pause-link').show();
            // Add the file to the list
            $uploadList.append('<li class="resumable-file-' + file.uniqueIdentifier + '">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span><br><div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemax="100"></div> </div><br><div class="alert alert-warning"> When File is "Completed" Proceed to Step 2 </div>');
            $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-name').html(file.fileName);
            // Actually start the upload
            resumable.upload();
        });
        resumable.on('fileSuccess', function (file, message) {
            // Reflect that the file upload has completed
            $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(Completed)');
        });
        resumable.on('fileError', function (file, message) {
            // Reflect that the file upload has resulted in error
            $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(file could not be uploaded: ' + message + ')');
        });
        resumable.on('fileProgress', function (file) {
            // Handle progress for both the file and the overall upload
            $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html;
            $('.progress-bar').css({width: Math.floor(resumable.progress() * 100) + '%'});
        });
    }

}

This uses the route: cupload

Activity icon

Started a new Conversation Route ID To Database Via Controller

Hi all. I have a multiple upload page that has the form that was submitted's id in. My issue is that I can't get the form->id or the id in the route to be submitted on the creation of a file upload in the database. I have tried $id, $form_id, $form->id in the controller and also sending the $form->id in the route when the user uploads but it is not picking it up.

/**
     * Saves the file
     *
     * @param UploadedFile $file
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function saveFile(UploadedFile $file)
    {
        $fileName = $this->createFilename($file);
        $fileAuth = Auth::user()->name;
        // Build the file path
        $filePath = "upload/client/".$fileAuth;
        $finalPath = storage_path("app/".$filePath);
        // Save to Database
        $file = new ClientFormFile;
        $file->filepath = storage_path("app/".$filePath).'/'.$fileName;
        $file->user_id = Auth::user()->id;
        $file->form_id = $form->id;
        $file->save();
        // Move the file name
        $file->move($finalPath, $fileName);
        return response()->json([
            'path' => $filePath,
            'name' => $fileName
        ]);
    }

The above is from pion/laravel-chunk-upload's example, and it works 100%. Had issues getting it to save the filename to the database and now that that is sorted, I can't get the form ID saved.

The user submits a form and then gets sent to:

Route::get('client-upload/upload/{form_id?}', '[email protected]')->name('client-upload.create');

Which is like: http://localhost/upload/public/client-upload/upload/2

So the ID is pulling through.

The upload view:

@extends('layouts.app')

@section('content')

<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
  <h1 class="h3 mb-0 text-gray-800"><i class="text-primary fas fa-plus"></i> Upload</h1>
  <a href="{{ URL::previous() }}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-angle-double-left fa-sm text-white-50"></i> Back</a>
</div>

<!-- Content Row -->
<div class="row">
  <div class="col-md-12 col-xs-12 col-lg-12">
    <div class="card shadow mb-4">
      <div class="card-header py-3">
        <div class="clear-fix">
          <div class="float-right">
            <div class="d-flex flex-row bd-highlight">
              <input type="hidden" value="$form->id">
            </div>
          </div>
          <div class="float-left">
            <h6 class="m-0 font-weight-bold text-primary">Upload your file below...</h6>
          </div>
        </div>
      </div>
      <div class="card-body">
        <div class="row">
            <div class="col-md-12 pt-3">
              <div class="text-center" >
                  <div id="resumable-error" style="display: none">
                      Resumable not supported
                  </div>
                  <div id="resumable-drop" style="display: none">
                    <p>
                      <p>
                        <i class="fas fa-caret-square-down fa-3x"></i>
                      </p>
                      <button class="btn btn-dark" id="resumable-browse" data-url="{{ route('cupload', $form->id) }}" >Click here to Upload</button>
                    </p>
                  </div>
                  <ul id="file-upload-list" class="list-unstyled"  style="display: none">

                  </ul>
                  <br/>
              </div>
            </div>
        </div>
    </div>
  </div>
</div>
@endsection

On the route I have tried adding {{route('cupload', $form->id)}} That does not work. The full upload route is:

Route::post('client-upload/upload/{form_id?}', '[email protected]')->name('cupload');

Here is the full controller for the upload:

<?php

namespace App\Http\Controllers;

use App\ClientUpload;
use App\ClientFormFile;
use App\Form;
use Storage;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;

class ClientUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $forms = Form::all();
        return view('uploads.client.index',
        ['forms'=>$forms]
        );
    }

    public function create($id)
    {
        $form = Form::find($id);
        return view('uploads.client.create', [
            'form' => $form
        ]);
    }

    /**
     * Handles the file upload
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws UploadMissingFileException
     * @throws \Pion\Laravel\ChunkUpload\Exceptions\UploadFailedException
     */
    public function upload(Request $request) {
        // create the file receiver
        $receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
        // check if the upload is success, throw exception or return response you need
        if ($receiver->isUploaded() === false) {
            throw new UploadMissingFileException();
        }
        // receive the file
        $save = $receiver->receive();
        // check if the upload has finished (in chunk mode it will send smaller files)
        if ($save->isFinished()) {
            // save the file and return any response you need, current example uses `move` function. If you are
            // not using move, you need to manually delete the file by unlink($save->getFile()->getPathname())

            return $this->saveFile($save->getFile());
        }
        // we are in chunk mode, lets send the current progress
        /** @var AbstractHandler $handler */
        $handler = $save->handler();
        return response()->json([
            "done" => $handler->getPercentageDone(),
            'status' => true
        ]);
    }

    /**
     * Saves the file
     *
     * @param UploadedFile $file
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function saveFile(UploadedFile $file)
    {
        $fileName = $this->createFilename($file);
        $fileAuth = Auth::user()->name;
        // Build the file path
        $filePath = "upload/client/".$fileAuth;
        $finalPath = storage_path("app/".$filePath);
        // Save to Database
        $file = new ClientFormFile;
        $file->filepath = storage_path("app/".$filePath).'/'.$fileName;
        $file->user_id = Auth::user()->id;
        $file->form_id = $form->id;
        $file->save();
        // Move the file name
        $file->move($finalPath, $fileName);
        return response()->json([
            'path' => $filePath,
            'name' => $fileName
        ]);
    }
    /**
     * Create unique filename for uploaded file
     * @param UploadedFile $file
     * @return string
     */
    protected function createFilename(UploadedFile $file)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = str_replace(".".$extension, "", $file->getClientOriginalName()); // Filename without extension
        // Add timestamp hash to name of the file
        $filename .= "." . $extension;
        return $filename;
    }

}

The database is as so:

        $table->bigIncrements('id');
            $table->integer('form_id')->unsigned();
            $table->foreign('form_id')->references('id')->on('forms');
            $table->string('filepath');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');

The user_id and filepath works fine, it's just getting the form->id to pass in. Any help would be appreciated!

Activity icon

Replied to Que A Artisan Command

Morning, there are no logs. Also the hi does return but only the backup-temp folder is created and that is all.

Aug
30
2 months ago
Activity icon

Replied to Que A Artisan Command

When running in console it does, when running as so just makes backup-temp folder. So it is doing something, but stops.

Activity icon

Replied to Que A Artisan Command

Im still new to this, so honestly I wouldn't know.

Activity icon

Started a new Conversation Que A Artisan Command

I have spatie/back-up setup, the command php artisan backup:run works 100% on the console. I would like to have a route that when pressed it does this in the background.

I am completely new to ques. I created a job, and inserted the command in the handle. Then have my route dispatch the job, it runs a little then goes to blank page and does nothing.

env

QUEUE_CONNECTION=database

job - BackUp.php

<?php

namespace App\Jobs;

use Illuminate\Support\Facades\Artisan;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class BackUp implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Artisan::call('backup:run');
    }
}

web.php

//Backup
Route::get('admin/backup', function() {
    App\Jobs\BackUp::dispatch();
})->name('backup');

Even running the command directly in the route ends with a blank page.

Aug
29
2 months ago
Activity icon

Started a new Conversation Pivot Table With Extra Fields

I have a pivot table that gets populated by another controller. It has: user_id, team_form_id, file_upload.

The user_id and file_upload gets populated by another controller. I need to get the team_form_id populated by a form that is submitted. The user uploads multiple files and it gets stored, the person then submits the form - I have had to use 2 controllers as the uploads are chunked.

I would like to check where the user_id is = to Auth::user()->id and where the team_form_id is null to be populated with the form id that is being submitted:

public function store(Request $request)
    {
        $teamform = new TeamForm;
        $teamform->team_form_id = $request->team_form_id;
        $teamform->teamupload = $request->teamupload;
        $teamform->user_id = Auth::user()->id;

        $teamform->save();

        if ($teamform->save()) {
            $teamuser = Auth::user()->id;
            $teamform->teamlog()->sync($teamuser);
        }

        return redirect(route('team-form.index'))->with('success', 'Form added successfully');
    }

The model for the file upload is TeamFormFIle. I have tried the below:



        if ($teamform->save()) {
            $files = TeamFormFile::find('user_id' == Auth::user()->id);
            if ($files->team_form_id == null) {
                foreach($files as $file) {
                    $file->team_form_id = $teamform->id;
                    $file->save();
                }
            }
        }

So basically loop through the records find the user that is currently logged in and submit the form id to the team_form_id that are null.

Aug
28
2 months ago
Activity icon

Replied to Can't Save Final Moved File Path To Database

Hi managed, to fix the issue - thank you for your efforts though

protected function saveFile(UploadedFile $file) { $fileName = $this->createFilename($file); // Build the file path $fileAuth = Auth::user()->name; // Build the file path $filePath = "upload/team/".$fileAuth; $finalPath = storage_path("app/".$filePath);

    // move the file name
    $file->move($finalPath, $fileName);
    $file = new File;
    $file->filename = storage_path("app/".$filePath).'/'.$fileName;
    $file->save();
    return response()->json([
        'path' => $filePath,
        'name' => $fileName
    ]);
}
Aug
19
3 months ago
Activity icon

Replied to Where Are You All From?

Sandton, Gauteng, South Africa

Aug
17
3 months ago
Activity icon

Replied to Selection To Filter Other Selection

Found a solution :)

<script type="text/javascript">
//Channels filter
var $company = $( '#company' ),
    $channels = $( '#channels' ),
    $options = $channels.find( 'option' );

$company.on( 'change', function() {
  $channels.html( $options.filter( '[data-company-id="' + this.value + '"]' ) );
} ).trigger( 'change' );
</script>
Aug
15
3 months ago
Activity icon

Replied to Selection To Filter Other Selection

I found this approach but have no idea how to mix it with your info:

$(document).on('change', '.country', function () {
    if ($(this).val() == $(this).data('current-countryCode')) {
        $('#states').next(".select2-container").show();
    }
    else {
        $('#states').next(".select2-container").hide();
    }
});
Activity icon

Replied to Selection To Filter Other Selection

I am afraid I am still such a noob, tried various ways and the style="display:none" still shows all the items. I may have forgotten to mention that I am using select2. Even with the company selected all items shown. Would you mind going into full detail, I think my JS is still to amateur for this.

Activity icon

Replied to Pivot Wont Update

sorted.

Activity icon

Replied to Pivot Wont Update

it indeed has channels[] The form in the edit.blade.php is being submitted normaly.

<div class="col-md-4">
                        <label for="channels">Channels</label>
                        <select class="js-tags form-control" name="channels[]" multiple="multiple">
                        @foreach($channels as $channel)
                            <option value="{{ $channel->id }}"{{ in_array($channel->id, $form->channels->pluck('id')->toArray()) ? " selected" : "" }}>{{ $channel->title }}</option>
                        @endforeach
                        </select>
                    </div>
Activity icon

Replied to Pivot Wont Update

I am using this to show the selected channels, could this be the issue:

@section ('scripts')
<script>
$('.js-tags').select2();
$('.js-tags').select2().val({!! json_encode($form->channels()->pluck('channels.id')->toArray()) !!}.trigger('change'));
</script>
@endsection
Activity icon

Replied to Selection To Filter Other Selection

Thank you kindly, I will try this out and give feedback :D

Activity icon

Started a new Conversation Selection To Filter Other Selection

Hi,

I have 2 selection boxes - I am using Laravel:

<div class="col-md-2">
                        <label for="company">Company</label>
                        <select class="form-control" name="company" id="company">
                            @if($companies->isEmpty())
                            <option selected>None</option>
                            @else
                            <option selected>Please Select</option>
                            @endif
                            @foreach($companies as $company)
                            <option value="{{$company->id}}">{{$company->title}}</option>
                            @endforeach
                        </select>
                    </div>
<div class="col-md-4">
                        <label for="channels">Channels</label>
                        <select class="js-tags form-control" name="channels[]" multiple="multiple">
                        @foreach($channels as $channel)
                            <option value="{{$channel->id}}">{{$channel->title}}</option>
                        @endforeach
                        </select>
                    </div>

The channels has a company_id in the database. When Company with id 1 is selected I want only the channels with the company_id 1 to show in the selection menu, how can one make this work?

Activity icon

Replied to Pivot Wont Update

Adding ->first() then gives a

Call to a member function update() on boolean

error

Activity icon

Started a new Conversation Pivot Wont Update

Hey, I am using Select2 for my selection of channels. I can store the channels on the pivot table, but keep getting an error call to member on integer when updating on the several solutions I have tried.

Update in controller as current:

/**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $form = Form::where('id', $id)->update([
            'start_date' => $request->input('start_date'),
            'end_date' => $request->input('end_date'),
            'event' => $request->input('event'),
            'editing' => $request->input('editing'),
            'additional_instructions' => $request->input('additional_instructions'),
            'company_id' => $request->input('company'),
            'brand_id' => $request->input('brand'),
            'frequency' => $request->input('frequencies'),
            'media_types' => $request->input('media_types'),
            'type_coms' => $request->input('type_communication'),
            'upload' => $request->input('upload'),
        ]);

        if ($form->update()) {
            $channel_ids = Input::get('channels');
            $form->channels()->sync($channel_ids);
        }

        return redirect()->route('client-form.index')->with('success', 'Form updated successfully');
    }

My Model to pivot table

public function clientlog()
    {
        return $this->belongsToMany(User::class, 'client_dates')->withTimestamps();
    }

JS Scripts

@section ('scripts')
<script>
$('.js-tags').select2();
$('.js-tags').select2().val({!! json_encode($form->channels()->pluck('channels.id')->toArray()) !!}.trigger('change'));
</script>
@endsection

and

//Select2 Pills
$(document).ready(function() {
  $('.js-tags').select2();
});

View:edit

<div class="col-md-4">
                        <label for="channels">Channels</label>
                        <select class="js-tags form-control" name="channels[]" multiple="multiple">
                        @foreach($channels as $channel)
                            <option value="{{ $channel->id }}"{{ in_array($channel->id, $form->channels->pluck('id')->toArray()) ? " selected" : "" }}>{{ $channel->title }}</option>
                        @endforeach
                        </select>
                    </div>

migration if need be

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFormChannelTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('form_channel', function (Blueprint $table) {
            $table->integer('form_id')->unsigned();
            $table->integer('channel_id')->unsigned();
            $table->primary(['form_id', 'channel_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('form_channel');
    }
}

Any help would be great, the youtube tutorial I followed does not update the table and also gives an integer error

Aug
06
3 months ago
Activity icon

Replied to Get ID And Upload String From DB

@foreach($teamupload as $team)
                    @if($team->team_form_id === $form->id)
                    <a class="btn btn-outline-primary" href="{{ route('teamDownload', ['user' =>  $team->users->name, 'file' => $team->teamupload]) }}"><i class="fas fa-download"></i> Download </a>
                    @endif
                    @endforeach

Sorted Leaving this here for those who may have the same noobie issue :)

Activity icon

Started a new Conversation Get ID And Upload String From DB

Hi,

I have 2 main models I am using to pass and get information.

  1. Form = DB: forms
  2. TeamForm = DB: teamforms

My teamform has a team_form_id, user_id and teamupload

I have used the belongsToMany relationship in both Form.php and TeamForm.php for other methods used in my controllers.

I want to access from form/1 (1 being the id), the teamform where the form_id is the same and get the info for users and teamupload

TeamForm.php

//Team Form Relationship
    public function teams()
    {
        return $this->belongsTo('App\TeamForm', 'team_form_id');
    }

//Allow on Forms
    public function users()
    {
        return $this->belongsTo('App\User', 'client_id');
    }

TeamForm.php

//Allow Form Access
    public function forms()
    {
        return $this->belongsTo('App\Form', 'team_form_id');
    }

    //Allow User on Form
    public function users()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

FormController

public function show($id)
    {
        $form = Form::find($id);
        $channels = Channel::all();
        $team = TeamForm::all();
        return view('forms.client.show', ['form'=>$form, 'channels'=>$channels, 'team'=>$team]); 
    }

I have tried $form->teams->users->name and $forms->teams->teamupload, alternating to $team->users->name and so on. These are being passed into a route which I am using for uploads, though these result with Property [users] does not exist on this collection instance.

I have used the relationships in my create, edit and index with no issues

Activity icon

Replied to Can't Download File

Thank you!!! you a god send, thank you for the patience and help!!!

Activity icon

Replied to Can't Download File

<a href="{{ route('clientDownload') . '/' . $teamform->forms->users->name . '/' . $teamform->forms->upload }}" class="btn btn-outline-primary float-right" target="_blank"><i class="fa fa-download"></i> Download </a>
Activity icon

Replied to Can't Download File

Hey again, I have read the documentation and a few tutorials. I am just not getting the hang of this. I need to pass 2 variables to the route - $teamform->forms->users->name and $teamform->forms->upload.

web.php

//Team Download
Route::get('team-form/{file}', '[email protected]')->name('clientDownload');

controller

public function downloadClientFile() {
        return response()->download(storage_path('/app/upload/client/'));
    }

I looked at this tutorial and understand the concept: https://stackoverflow.com/questions/20415444/download-files-in-laravel-using-responsedownload

But I just don't see how it will work with 2 variables, I am still very new to Laravel and some of the methods are hard to recreate with what I would like.

Activity icon

Replied to Can't Download File

Herewith screengrab: https://snag.gy/Lj3lhB.jpg

Activity icon

Replied to Can't Download File

Hi thank you for that, I have done php artisan storage:link. The files are uploaded by one user with a role but needs to be accessible to another user with another role.

example user with role team user with role client.

These files are not to be public but they need to be downloaded. The client uploads a file, the team download it and reupload the edited file which the client should beable to download.

Would the route support this?

I am currently using storage/app/upload/user_role (team or client)/user name/ then the file:

{{ storage_path('upload/client/' . $teamform->forms->users->name . '/' . $teamform->forms->upload) }}
Activity icon

Replied to Can't Download File

When hovering over the link it says file:// and then the link, could this be the problem?

Activity icon

Replied to Can't Download File

Thank you, just tried your solution and it isn't doing anything. Mmmm... I also tried adding app/ and still nothing. When using the devtools it says file is not found, I have checked and the link is indeed correct and corresponds to the file directory.

Activity icon

Replied to Can't Download File

I have made a syslink in the public folder

Activity icon

Started a new Conversation Can't Download File

Hi, I am battling to download a file in my storage directory

Directory is: storage/app/upload/client/

after the client/ the stored client_id - > user->name is used and then the file name. I currently have this as the download button, but it isn't rendering anything.

<a href="{{storage_path()}}/upload/client/{{$teamform->forms->users->name}}/{{$teamform->forms->upload}}" class="btn btn-outline-primary float-right" target="_blank"><i class="fa fa-download"></i> Download </a>
Aug
03
3 months ago
Activity icon

Replied to Data Too Long For Column 'job_description'

Ohh okay, thank you for explaining that. Learning slowly :)

Activity icon

Replied to Can't Save Final Moved File Path To Database

here the entire controller:

<?php

namespace App\Http\Controllers;

use App\ClientUpload;
use App\Form;
use Storage;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;

class ClientUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('uploads.client.index');
    }

    public function create(){
        $forms = Form::all();
        return view('uploads.client.create', [
            'forms'=>$forms
        ]);
    }    

    /**
     * Handles the file upload
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws UploadMissingFileException
     * @throws \Pion\Laravel\ChunkUpload\Exceptions\UploadFailedException
     */
    public function upload(Request $request) {
        // create the file receiver
        $receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
        // check if the upload is success, throw exception or return response you need
        if ($receiver->isUploaded() === false) {
            throw new UploadMissingFileException();
        }
        // receive the file
        $save = $receiver->receive();
        // check if the upload has finished (in chunk mode it will send smaller files)
        if ($save->isFinished()) {
            // save the file and return any response you need, current example uses `move` function. If you are
            // not using move, you need to manually delete the file by unlink($save->getFile()->getPathname())
            return $this->saveFile($save->getFile());
        }
        // we are in chunk mode, lets send the current progress
        /** @var AbstractHandler $handler */
        $handler = $save->handler();
        return response()->json([
            "done" => $handler->getPercentageDone(),
            'status' => true
        ]);

        return $filePath;
    }
    
    /**
     * Saves the file
     *
     * @param UploadedFile $file
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function saveFile(UploadedFile $file)
    {
        $fileName = $this->createFilename($file);
        // Group files by the date (week
        $dateFolder = date("Y-m-W");
        // Build the file path
        $filePath = "upload/{$dateFolder}/";
        $finalPath = storage_path("app/".$filePath);
        // move the file name
        $file->move($finalPath, $fileName);
        return response()->json([
            'path' => $filePath,
            'name' => $fileName
        ]);
    }
    /**
     * Create unique filename for uploaded file
     * @param UploadedFile $file
     * @return string
     */
    protected function createFilename(UploadedFile $file)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = str_replace(".".$extension, "", $file->getClientOriginalName()); // Filename without extension
        // Add timestamp hash to name of the file
        $filename .= "_" . md5(time()) . "." . $extension;
        return $filename;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $clientupload = new ClientUpload;
        $clientupload->form_id = $request->form_id;

        $clientupload->save();

        return redirect(route('client-upload.index'))->with('success', 'Upload added successfully.');

    }
}