david001

Experience

9,150

1 Best Reply Awards

  • Member Since 2 Years Ago
  • 2 Lessons Completed
  • 5 Favorites

11th February, 2018

david001 left a reply on Communications Between Siblings (Vue+Laravel Form) • 1 week ago

Anybody who can help me

10th February, 2018

david001 started a new conversation Communications Between Siblings (Vue+Laravel Form) • 1 week ago

I have send statusand user_id as a props form parent to one sibling. Now i want to transfer samething to another sibling.

I Have simple 3 multistep form:form1, form2 and form3 In form1 i have login information,form2 consist personal information and form3 has career information.

i have 3 tables namely users to insert login information from form1, profiles table to store personal information from form2 and careers table to store careeer information.

In first step after completion of form1,i will grab his email,find id(user_id)last inserted id,hide form1, pass form2 status(true status) and user_id to form2 as props.

In step2 now form1 and form3 is hidden,form2 is display. Now i can save form2 information because i have user_id as props and my form2 status is true.

problem:After completion of form2, my form3 should be displayed.so i have to pass form3 status(true status) and user_id after successfull insertion of form2 data,probably raising an event. I did but my form3 is not displayed after form2 completion.

My first component is Employee.vue consist login information, 2nd is Employee2.vue consist personal info,3rd is Employee3.vue consist career info.

in index.blade.php i have

 <employee>     </employee>//first form

Employee.vue

<template>
    
//SENDING DATA to FORM2(employee2)
    <employee2 :form2="form2" :user_id="user_id" "></employee2>


    <form action="#" id="loginInfo" v-if="form1">
    

       <div class="form-group">
            <label for="username">Username:</label>
            <input type="text" name="username" v-model="loginUserInfo.username" class="form-control">
            <p v-if="error.username">
                <span v-for="err in error.username" class="label label-danger">{{ err }}
                </span>
        </p>
            
        </div>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="text" name="email" v-model="loginUserInfo.email" class="form-control">
            <p v-if="error.email">
                <span v-for="err in error.email" class="label label-danger">{{ err }}
            </span>
            </p>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" name="password" v-model="loginUserInfo.password" class="form-control">
            <p v-if="error.password" class="list-unstyled">
                <span v-for="err in error.password" class="label label-danger">{{ err }}</span>
            </p>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-success"@click.prevent="loginInfo">Continue</button>
        </div>
    </form>

    
    


        
    </div>
    <!--end of col-md-8-->

</template>


<script>
    export default{
        data(){
            return{
                error:[],
                
                success:false,
                form1:true,
                form2:false,
                form3:false,

                loginUserInfo:
                {
                    username:'',
                    email:'',
                    password:'',
                },
                
                user_id:'',

            
            }
        },
        methods:{
                loginInfo()
                {
                    axios.post('/employee/create',this.loginUserInfo)
                        .then((response)=>{
                            console.log(response.data);
                            this.user_id =  response.data;
                            this.form1 = false;//disaplying form1
                            this.form2 = true;//enabling form2

                            

                    }).catch(error=>{
                        this.error = error.response.data
                    });
                },

            }


    }
</script>

form2

Employee2.vue



<!--Form2-->
<template>


    <form action="#"  v-if="form2">

        
        <h1>Personal Information</h1>
        <small>The field marked with * refers to required information!</small>

        <div class="form-group">
            <div class="col-md-4">
            <label>First name *:</label>
                <input type="text" name="first_name" v-model="personalInfo.first_name" class="form-control">
                <p v-if="error.first_name" class="list-unstyled">
                    <span v-for="err in error.first_name" class="label label-danger">{{ err }}</span>
                </p>
            </div>
        </div>

            //..................

    <div class="form-group">
    
        <button class="btn btn-success" @click.prevent="personalInfoCreate">Continue</button>
    </div>

</form>

</template>
<script>
import Bus from '../../bus.js'
    export default{

        props:['form2','user_id'],
        data(){
            return{
                error:[],
                
                success:false,
            //  form3:false,
                
            

                
                personalInfo:
                {
                    first_name:'',
                    
                },
                

            }
        },
        methods:{
                
            personalInfoCreate(){

                axios.post('/employee/personalInfo/create/' + this.user_id,this.personalInfo) 
                       .then((response) => {
                    console.log(response)
                    this.form2 = false;//disabling form2
                    
                       this.form3 = true;//enabling form3

                    Bus.$emit('form3',this.form3)  //passing form3 status as event 

                 }).catch(error=>{
                    this.error = error.response.data
                 });
            },
            }


    }
</script>

Form3:

Employee3.vue
<template>
    <!--form3-->

      <form action="#" " v-if="form3">

        <div class="form-group">
            <label>Career Plan*</label>
            <textarea class="form-control" v-model="career.career_plan"></textarea>
        </div>

        

        <div class="form-group">
            <button type="submit" class="btn btn-success" @click.prevent="careerInfo">Continue</button>
        </div>


      </form>       

</template>
    
<script>
import Bus from '../../bus.js'

    export default{
        
        data(){
            return{
                error:[],
                
                
            
                career:
                {
                    career_plan:'',
                    
                }
            }
        },
        methods:{
                
        

            careerInfo() {
                
            },
            created(){
                    Bus.$on('form3',(data)=>{
                        this.form3=data;  // to enable form3 after completion of form2
                        
                    })
                }



    }
</script>

I havebus.jsin Components directory

import Vue from 'vue'

export default new Vue()

My question is how can i pass form3 status(true) and user_id from Employee2.vue(form2) to Employee3.vue(form3). I did like above it worked upto Employee2.vue but after completion of form2(Employee2.vue) form3 is not shown/invisible.

david001 left a reply on Simple Multistep Form • 1 week ago

i have done something like that and it works fine.but i want to go in abit advance level. i pass form2 status(true) and user_id to from2 after completion of form1, it worked and again i emit event after successfull insertion of form2 data in db. I only emitted form3 status(true) from form2. But my form3 never displayed after form2

in index.blade.php //component Thanks for your suggestions

david001 left a reply on Simple Multistep Form • 1 week ago

@Borisu what iam trying to do is that. i want to send form2 status(true) and user_id as a props to form2,so that after completion of form1 it would display form2 and with user_id from props i can insert data in another table. Again from form2 to reach form3 i should pass form 3 status(true) to display form3 after completion of form2 and user_id as event. I made bus.js


import Vue from 'vue'

export default new Vue()

in form 2:

//after success of form2 insetion
//.........
import Bus from '../../bus.js'
axios.post('', {})
    .then(response => {
......
 this.form3 = true;
 Bus.$emit('displayform3',this.form3)

});

in form 3:to display form3

import Bus from '../../bus.js'
mounted() {
            
            console.log('Component mounted.')

            Bus.$on('displayform3',(data)=>{
                        console.log(data)
                        data = this.form3;
                        
                    })

        }

My problem:after completion of form2, my form3 is not displayed

9th February, 2018

david001 left a reply on Simple Multistep Form • 1 week ago

@Borisu can you please give me an idea,how can i make three different components for three different form. do i have to use BUS/Event for that. I want to make my code cleaner with different components.

david001 left a reply on Simple Multistep Form • 1 week ago

edited

7th February, 2018

david001 left a reply on Simple Multistep Form • 1 week ago

i have posted full questions but only half code is displayed.i dont know why this is happening

david001 started a new conversation Simple Multistep Form • 1 week ago

Route:

Route::post('employee/create','[email protected]');
Route::post('employee/personalInfo/create','[email protected]');

6th February, 2018

david001 left a reply on Validation Not Working • 1 week ago

If i do this:

 $this->validate($request, [
                'name123' => 'required',
            ]);

name123 is not my html field. it detect and gives error name123 field not existin console. however is does not work for my actual field

 $this->validate($request, [
                'name' => 'required',
            ]);

<input type="text" name="name" v-model="userInfo.name">
            <input type="file" name="image"  v-on:change="onFileChange">
            <button type="submit" class="btn btn-success"@click.prevent="attachmentCreate">Upload</button>

david001 left a reply on Validation Not Working • 1 week ago

Laravel 5.5

david001 left a reply on Validation Not Working • 1 week ago

yes i tried ,but it gave error method validate does not exist

david001 left a reply on Validation Not Working • 1 week ago

@wilk_randall @VijayKadiyam If i do this:

 $this->validate($request, [
                'name123' => 'required',
            ]);

name123 is not my html field. it detect and gives error name123 field not existin console. however is does not work for my actual field

 $this->validate($request, [
                'name' => 'required',
            ]);

<input type="text" name="name" v-model="userInfo.name">
            <input type="file" name="image"  v-on:change="onFileChange">
            <button type="submit" class="btn btn-success"@click.prevent="attachmentCreate">Upload</button>

david001 started a new conversation Validation Not Working • 1 week ago

I am trying to display validation error with vue js in laravel app. But my method ignores validation rule. i don't know why this is happening.

controller:

public function postStudent(Request $request)
    {
         $this->validate($request,[
            'name' => 'required',  
            'image'=>'required' 
          
        ]);


       if($request->hasFile('image')){
            $uplodedFile = $request->image;
            $fileName = $uplodedFile->store('public/images');
       
        $student = new Student;
        $student->name = $request->name;
        $student->image = $fileName;
        $student->save();
    }
        return "ok";

        
    }

Student.vue

<template>
    <div>
    
            <input type="text" name="name" v-model="userInfo.name">

            <input type="file" name="image"  v-on:change="onFileChange">

        <button type="submit" class="btn btn success"@click.prevent="attachmentCreate">Upload</button>
    
</div>
</template>

<script>
export default{
    data(){
        return{
            error:[],

            userInfo:
            {
                image:null,
                name:null,
            }

        }
    },
    methods:{
        onFileChange(event){
            this.userInfo.image = event.target.files[0]

        },
        attachmentCreate() {
            const form = new FormData();
            form.append('image',this.userInfo.image);
            form.append('name',this.userInfo.name);

            

            axios.post('step-1',form)
                    .then((data)=>{
                console.log("ok")
               
                }).catch(error => {
                   
                            this.error = error.response.data;
                            console.log(this.error);
                       
                    
                })
            }
     
    }
}

</script>

if i submit the form without the input ,it should show some error message in console(ie:name field is required),but i am not getting any error. i got ok response only . Please help me to display error message

16th January, 2018

david001 started a new conversation Route Not Working: Page Not Found L5.5 • 1 month ago

I have just downloaded Laravel5.5 and i have some error with routes I have routes in web.php

//working routes Route::get('/', '[email protected]')->name('home'); Route::get('{slug}','[email protected]')->name('show');

//not working routes Route::get('/home', '[email protected]')->name('home'); // Route::get('pro','[email protected]')->name('pro');

Route::get('/test', function () { return "ok"; });//this is not workig

Auth::routes();

when i open /test instead of returning OK it giver error Sorry, the page you are looking for could not be found.

9th January, 2018

david001 started a new conversation How To Convert To Eloquent • 1 month ago

my victims table has column district_id,incident_type_id etc my districts table has column name my incidents table has column incident_type

I have a Sql Query like this

Route::get('/total', function () {
    $users = \DB::table('victims')
                    ->join('districts','victims.district_id','=','districts.id')
                    ->join('incidents','victims.incident_type_id','=','incidents.id')
                     ->select('districts.name','incidents.incident_type',\DB::raw('count(*) as total'))
                     ->groupBy('district_id','incident_type_id')
                     ->orderBy('district_id','ASC')
                     //->having('total','>',1)
                     ->get();
                   //  dd($users);
    foreach($users as $user){
        echo 'total' .ucfirst($user->incident_type). 'case in district'.'&nbsp;'.$user->name.'is'. '&nbsp;'.$user->total
        .'</br>';
    }
});

//its output is
total Rape case in district A is 2
total Murder case in district A is 2
total Rape case  in district B is 1
total Rape case  in district cis 3

i want similar output . so i have relationship like this

Victim.php

class Victim extends Model
{
    

    public function district(){
        return $this->hasOne(District::class,'id','district_id');
    }
    public function incident(){
        return $this->hasOne(Incident::class,'id','incident_type_id');
    }
   
    
}

District.php

class District extends Model
{
   
}

Incident.php

class Incident extends Model
{
   
  
}

//Here i want similar out put as above,but its not working

Route::get('/total', function () {
    $users = Victim::withCount('district.incident')
          ->groupBy('district_id','incident_type_id')->get();

          foreach($users as $user){
            echo 'total' .$user->incident->incident_type. 'case in district'.'&nbsp;'.$user-
                            >district->name.'is'. '&nbsp;'.'total'
        .'</br>';
          }
         
});

I am not getting above output.How can i get output as above

8th January, 2018

david001 started a new conversation Middleware Protecting Routes • 1 month ago

How to protect routes with middleware for following conditions

i have users table and roles table

users table id name email role_id

roles table

id          name          slug
1           admin         admin
2          student      student
3          teacher      teacher

In User.php

 public function role()
 {
         return $this->hasOne(Role::class,'id','role_id');
 }

RoleGate.php

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class RoleGate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$role)
    {
        if ($request->user() && $request->user()->role && $request->user()->role->slug === $role) {
                return $next($request);
         }
        return redirect('/login');
    }
}

Route:

//for student
 Route::middleware(['role:student'])->group(function () {
    Route::get('student',function(){
        return"student";
    });
});

//for teacher
 Route::middleware(['role:teacher'])->group(function () {
    Route::get('teacher',function(){
        return"teacher";
    });
});

//for admin
 Route::middleware(['role:admin'])->group(function () {
    Route::get('admin',function(){
        return"admin";
    });
});

This works fine but i want to make student and teacher route visible to admin.Admin can view all route

How can i modify my logic inside handle() method

7th January, 2018

david001 left a reply on Filter Products With Checkbox • 1 month ago

ok i will follow your steps.Thanks

5th January, 2018

david001 started a new conversation Multiple File Upload Validation • 1 month ago

How can validate multiple file before uploading

This is the code to upload multiple file,but i want to validate before upload
public function caseFileStore(Request $request)
    {    
        $files = [];
        foreach ($request->file('crFile') as $file) {
            if($file->isValid()) {
            $path = $file->store('public/files');

        $files [] = [
            'file_name' => $file->getClientOriginalName(),
            'file_path' => $path,
        
            'description'=>'something',
            'created_at' => $now = Carbon:: now()->format('Ymd H: i: s'),
            'updated_at' => $now,
        ];
    }
}

       File::insert($files);

FileValidationRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FileValidationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        'crFile' = > 'required file |max: 2000' 
    }
}

view:

<form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">{{ csrf_field() }}
                        <input type="file" name="crFile[]" class="">
                        <input type="file" name="crFile[]" class="">
                        <input type="file" name="crFile[]" class="">
                        <br><button type="submit" class="btn btn-default ">Upload File</button>
                    </form>

4th January, 2018

david001 started a new conversation Json Field In Phpmyadmin • 1 month ago

I am using phpmyadmin I want to store lot of metadata about user profile as JSON $table->json('meta')->nullable(); Can i use this inphpmyadmin

3rd January, 2018

david001 left a reply on Export All Search Results • 1 month ago

Thanks,well explained

david001 left a reply on Export All Search Results • 1 month ago

@Talinon That's fine ,but how can i get dynamic date here

  $from = Session::get('cases_fromDate', '2018-01-01');  // dynamic date
    $to = Session::get('cases_toDate', '2018-01-03');// dynamic date

I did like this but got error:

public function export(Request $request){
       
    $from = \Session::get('cases_fromDate', $request->get('from'));  // here dynamic date
   /// return $from;

    $to = \Session::get('cases_toDate', $request->get('to'));

    $items = Case::whereDate('created_at','>=', $from)
        ->whereDate('created_at','<=', $to)->get();

      \Excel::create('items', function($excel) use($items) {
          $excel->sheet('ExportFile', function($sheet) use($items) {
              $sheet->fromArray($items);
          });
      })->export('xls');
    }

david001 started a new conversation Export All Search Results • 1 month ago

I want to download all the search results in xls format. For this i have used maatwebsite/excel package

Route to export xls

Route::post('export-search-results', '[email protected]')->name('download');

Route to search result

Route::get('cases','[email protected]');

my view

 <form action="/cases" method="GET">
    From:<input type="date" name="from">
    To:<span><input type="date" name="to">
    <button type="submit" class="btn btn-success btn-sm">Search</button></span>
</form>

<a href="{{route('download')}}">Export File</a>

<table class="table table-striped">

    <thead>
      <tr>
    
        <th>Full name</th>
        <th>Email</th>
        <th>Address</th>
       //.................
       
      </tr>
    </thead>
    <tbody>
      @if($cases->count())
        @foreach($cases as $case)
        <tr>
          
         <td>{{ $case->full_name }}</td>
          <td>{{ $case->email }}</td>
          <td>{{ $case->district }}</td>
          
        </tr>
        @endforeach
    @else
            <td><b>No record found.</b></td>
       @endif

     
     {!! $cases->appends(Request::only(['from'=>'from', 'to'=>'to']))->render() !!}

controller:

//search record
public function index(){
    $cases = Case::whereDate('created_at','>=',$from)
          ->whereDate('created_at','<=',$to)->paginate(6);
    return view('case.index',compact('cases'));
}

//export file
 public function export(Request $request){
        
      $items = Case::whereIn('id',[1,2,3,4,5]);//how to get $request->id here of searched results
      \Excel::create('items', function($excel) use($items) {
          $excel->sheet('ExportFile', function($sheet) use($items) {
              $sheet->fromArray($items);
          });
      })->export('xls');
    }

for example my current url is like this localhost:8000/cases?from=2018-01-01&to=2018-01-03 Now i want to download/export xls all results found between this range

1st January, 2018

david001 left a reply on Filter Data With Laravel • 1 month ago

well explained.Thanks a lot

david001 started a new conversation Filter Data With Laravel • 1 month ago

I need help in searching data with laravel i have a form with field date from,to and district input field

My form in view

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12">


<div class="container">
  <div class="panel panel-heading">All Registered Cases({{ $cases->count() }})
    <form action="/cases" method="GET">
    From:<input type="date" name="from">
    To:<input type="date" name="to">
    District:<input type="text" name="district" class="">
    <button type="submit" class="btn btn-success btn-sm">Search</button>
  </form>

  </div>
 

<div  class="panel panel-body">
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Token</th>
        <th>Full name</th>
        <th>Email</th>
        <th>Address</th>
        <th>View</th>
      </tr>
    </thead>
    <tbody>
      @if($cases->count())
        @foreach($cases as $case)
        <tr>
          <td>{{ $case->token }}</td>
          <td>{{ $case->full_name }}</td>
          <td>{{ $case->email }}</td>
          <td>{{ $case->district }}</td>
          <td><a href="{{ route('cases.show',[$case->id]) }}">Browse</a></td>
        </tr>
        @endforeach
      
      @else
        <td><b>No record found.</b></td>
      @endif
    </tbody>
  </table>
     {{--  {{ $cases->links() }} --}}
     
     {!! $cases->appends(Request::only(['from'=>'from', 'to'=>'to','district'=>'district']))->render() !!}

</div>


    </div>
  </div>
</div>
@endsection

Route: Route::get('cases','[email protected]');

CaseRepositories.php

public function allCases()
    {
        return Case::paginate(40);
    }

    public function searchCases(array $searchData)
    {
        $from = $searchData['from'];
        $to = $searchData['to'];
        $district = $searchData['district'];
        if(!empty($district)&&!empty($from)&&!empty($to)){
        $cases = Case::whereDate('created_at','>=',$from)
                        ->whereDate('created_at','<=',$to)
                        ->where('district',$district)
                        ->paginate(1);
                        return $cases;
        }else{
        $cases = Case::whereDate('created_at','>=',$from)
                        ->whereDate('created_at','<=',$to)
                       // ->where('district',$district)
                        ->paginate(1);  
                        return $cases;
        }
        
    }

Controller:

public function index(Request $request)
    {
        if($request->get('from')||$request->get('to')||$request->get('district')){
            $cases = $this->case->searchCases($request->all());
          // dd($cases);
                   return view('case.index',compact('cases'));

       }

        $cases = $this->case->allCases();
        return view('case.index',compact('cases'));
    }



I have two problem: First: How can i modify code in CaseRepositories.php and Controller.I want to write better logic if possible

Second: when all fields are not empty ie:from,to and district are provide pagination works fine

but Admin can filter data with only from and to date making district field empty.In such case pagination won't work.it gives error like this: Undefined index: district.How can i handle this error

30th December, 2017

david001 left a reply on Which Types Of Relationship Should Be Here • 1 month ago

Yes it is close to case

david001 left a reply on Which Types Of Relationship Should Be Here • 1 month ago

@Snapey Actually i wanted to replace Victim with Case but i got some error.On google i found that case is PHP reserved word it is use in Switch statement. Now Victim is creating lots of confusion for me.

If you know that Victim can be replace with Case with no error then please reply here

david001 started a new conversation Which Types Of Relationship Should Be Here • 1 month ago

I have table structure like this

victims                                follow_ups                                              users
id|>full_name|email       case_id|user_id |description              id|name

controller:

public function show($id)
 $case = Victim::find($id);
        return view('victim.show',compact('case'));

Model

Victim.php
class Victim extends Model
{
     public function followUP(){
     return $this->hasOne(FollowUp::class,'case_id');
    }
}
User.php
class User extends Authenticatable
{


}
FollowUp.php

class FollowUp extends Model
{
}

in show.blade.php

{{ $case->full_name }}
{{ $case->email }}

I can get description from follow_ups table like this {{ $case->followUP->description }} But how can i get name from users table {{ $case->followUP->user_id}}//i want to display name here from users table

what kind of relationship helps me to get name from users table in here {{ $case->followUP->user_id}}

29th December, 2017

david001 started a new conversation Type Error • 1 month ago

What is my mistake please help me my current url is http://localhost:8000/tasks/11 i have form in this route where i want to assign this task to user but i got error

Type error: Argument 1 passed to App\Repositories\OneRepositories::assignTo() must be of the type array, string given, called in C:\xampp\htdocs\project\app\Http\Controllers\TaskController.php on line 124

In OneRepositories .php

  public function assignTo(array $assignData,$id)
    {
        $taskId =  $this->task->findOrFail($id);
        $assignTo = new User;
        $assignTo->task_id = $taskId ;
        $assignTo->user_id = \Auth::user()->id;
        $assignTo->description = $assignData['description'];
        $assignTo->save();
        return $assignTo;
    }

in controller

class TaskController extends Controller
{
    protected $repoTask ;
    public function __construct(OneRepositories $repoTask )
    {
        $this->repoTask = $repoTask;
    }

 public function create(Request $request,$id){
        $this->repoTask ->assignTo($id);
        return redirect()->back();
    }
}

route:

Route::post('assign/task/{id}','@create')->name('assign.store');

Form:

<form action="{{ route('assign.store',[$case->id]) }}" method="POST">{{ csrf_field() }}

  

     
          <div class="form-group">

         <label for="recipient-name" class="col-form-label">Assign To:             
            
            </label>
         
            <select name="user_id" class="form-control" required>
              @foreach(\App\User::all() as $user)
                <option value="{{ $user->id}}">{{ ucfirst($user->name) }}
                </option>

              @endforeach

            </select> 

        </div>
          <div class="form-group">
            <label for="message-text" class="col-form-label">Descriptions:</label>
            <textarea name="description" class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
   
   
        <button type="submit" class="btn btn-primary">Save</button>
   
  </form>
    ```
Please help me to fix this issue

11th December, 2017

david001 started a new conversation How Map Of Country Is Made With Js • 2 months ago

I want to make a map and show some results.is there any api for this . i want to make this map https://election.ekantipur.com/ and show results when user hover on map. i search same map on highcharts.com but could not found. please share your idea about creating map .

10th December, 2017

david001 left a reply on Remove Unwanted Text From Database • 2 months ago

do {!! display here !! }

8th December, 2017

david001 left a reply on How To Query This • 2 months ago

doing this i got only name of district with zero crime ,although i have some crime in every district

 $districts = District::with([
    'cases' => function ($query) {
            $query->whereMonth('crime_date', date('m')) 
                    ->whereYear('crime_date', date('y'));
        },
    'cases.crime'
])->get();

i got this in controller writing above code

[
{
id: 1,
name: "A",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
cases: [ ]
},
{
id: 2,
name: "B",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
cases: [ ]
}
]

But writing this

 $districts =  District::with('cases.crime')->get();
return $districts;

i got this

[
{
id: 1,
name: "A",//name of district
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
cases: [   //registered cases
    {
    id: 1,
    crime_id: 1,
    district_id: 1,
    crime_date: "2017-12-31 00:00:00",
    created_at: "-0001-11-30 00:00:00",
    updated_at: "-0001-11-30 00:00:00",
crime: {//name of crime from crimes table
id: 1,
name: "Rape",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
},
{
id: 3,
crime_id: 4,
district_id: 1,
crime_date: "2017-12-31 00:00:00",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
crime: {
id: 4,
name: "Women trafficking",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
},
{
id: 4,
crime_id: 3,
district_id: 1,
crime_date: "2017-12-31 00:00:00",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
crime: {
id: 3,
name: "Murder",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
}
]
},
{
id: 2,
name: "B",//name of district from districts table
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
    cases: [   
    {
    id: 2,
    crime_id: 1,
    district_id: 2,
    crime_date: "2017-12-31 00:00:00",
    created_at: "-0001-11-30 00:00:00",
    updated_at:  "-0001-11-30 00:00:00",
    crime: {
    id: 1,
    name: "Rape",
    created_at: "-0001-11-30 00:00:00",
    updated_at: "-0001-11-30 00:00:00"
}
}
]
}
]

I want to show total crime and name of crime on particular district at the end of month For eg:->total crime in "A" district was 3 and name of crime are rape,murder,traficking on month december ->total crime in "B" district was 1 and name of crime are "rape" on month december //etc for 12 month in each district

Simillarly total crime in "A" district was 4 and name of crime are rape,murder,traficking,violence on month january

david001 left a reply on How To Query This • 2 months ago

@tykus I have updated according to yours but i got error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'crime_date' in 'where clause' (SQL: select * from `crimes` where `crimes`.`id` in (1, 2, 3, 4) and month(`crime_date`) = 12 and year(`crime_date`) = 17)```


its looking ```crime_date ```in ```crimes``` table, i  have ```crime_date``` in ```cases``` table

david001 started a new conversation How To Query This • 2 months ago

I am working in a project.for now lets say i have 3 tables "districts", "crimes" , "cases". Cases table holds all the registered cases.

Case.php

class Case extends Model
{
        protected $table = 'cases';
        protected $fillable=['person_name','crime_id ,'district_id','crime_date'];

}

District.php

class District extends Model
{
        protected $table = 'districts';
        protected $fillable=['name'];//name of districts like "A district","B district" etc


}

Crime.php

class Crime extends Model
{
        protected $table = 'crimes';
        protected $fillable=['name'];//name of different types of crime like rape,murder etc

}

My output at the end of month should look like below in report.blade.php

  District name   |total crime    | crime
   A                                  3                   rape
                                                            murder
                                                attempt to murder

   B                                  1                    rape

  C                                    0                    No crime reported 

ReportController.php

public function index(){
     
        //get above format result here
    return view('case.report');
}

I think group by district_id can give number of crime in that district Id I need to fetch district with total crimes reported and types of crime for a month Please help me

4th December, 2017

david001 started a new conversation Filter Products With Checkbox • 2 months ago

I have seen many e commerce site in which user can filter products by clicking checkbox. for example:let say there are different brand of mobile: like samsung,nokia,aCompany,bCompany,cCompany etc. Different colour ,size,memory.

when user check samsung checkbox pages display only samsumg mobile,when user further check 8Gb memeory checkbox ,page display samsung mobile with 8Gb memory and so on.

i want to implement such feature with jquery/Ajax and Laravel. Can you give me idea how this is done

29th November, 2017

david001 left a reply on Passing Coordinates From View To Controller • 2 months ago

how to check whether i am getting latitude or longitude or not in controller. suppose i want to display latitude(dd() ) send from post request from view

david001 started a new conversation Passing Coordinates From View To Controller • 2 months ago

I am getting latitude and longitude in view , but these are not passed in controller.Please help me to fix this issue.

js

<script>

        $(document).ready(function(){
            get_location();
        });

        function get_location()
        {
            if(navigator.geolocation)
            {
                navigator.geolocation.getCurrentPosition(function(position){

                        var latitude = position.coords.latitude;
                        var longitude = position.coords.longitude;



                        $.post('http://localhost/api/coordinates', 'latitude='+latitude+'&longitude='+longitude);

                });
            }
        }
</script>

Route: api.php


Route::post('/coordinates','[email protected]');
Route::get('/test','[email protected]');

controller:

public function getCoordinates(Request $request)
    {
      //  return"ok";

        $lat=$request->latitude;
        $lng=$request->longitude;
        return $lat;
    }

    public function showCoordinates(Request $request)
    {
        echo $this->getCoordinates($request);
    }

when i am in browser at localhost:8000/api/test i got blank page no any latitude

28th November, 2017

david001 left a reply on Delete File Dropzone+laravel • 2 months ago

yes it is not permanent solution

david001 started a new conversation Delete File Dropzone+laravel • 2 months ago

How to delete particular file form dropzone and database This is my upload function:

 public function postUpload(Request $request,$id)
    {
         
        $destinationPath = 'images'; 
        $fileName=  $request->file('file')->getClientOriginalName(); 
        
        $upload_success = $request->file('file')->move($destinationPath, $fileName); 
     if($upload_success){
      
            $image = new Image;
            $image->filename = $fileName ;
           
            $image->save();

      }

 }

This is my view js :

<script>
Dropzone.options.myAwesomeDropzone = {
            maxFilesize: 2, // Size in MB
            addRemoveLinks: true,
            removedfile: function(file) { 

            var name = file.name;   
            console.log(file.name);       
            $.ajax({
              headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
         },
            type: 'POST',
            url: '/delete',
            data: {filename:name},
            dataType: 'html'
        });
            var fileRef;
                return (fileRef = file.previewElement) != null ? 
                      fileRef.parentNode.removeChild(file.previewElement) : void 0;
            },


                success: function(file, response) {
                  alert(response);
                 
                },

                error: function(file, response) {
                      alert(response);
                      return false;
                }
        };



</script>

This works perfectly . when i click remove link in dropzone after uploading file it deletes image from database ,But my problem is if two images are of same name in db then one click deletes both image,which i don't want

obviously i can do like this $fileName= $request->file('file')->getClientOriginalName(); $newFileName=$fileName.time();

so filename may be unique in db. but i need to delete file as well and through dropzone i get orginal file name

This is my delete method:

public function delete(Request $request){    
    $filename =  $request->get('filename');//gives orginal file name eg:abc.jpg
    Image::where('filename',$filename)->delete();
    return "ok";
   }

david001 left a reply on Dropzone Js:response After Upload Success • 2 months ago

This script solve my problem

Dropzone.options.myAwesomeDropzone = { maxFilesize: 2, // Size in MB addRemoveLinks: true, removedfile: function(file) {
                 // var name = file.name;        

// $.ajax({ // type: 'POST', // url: 'delete.php', // data: "id="+name, // dataType: 'html' // });

          var fileRef;
          return (fileRef = file.previewElement) != null ? 
                  fileRef.parentNode.removeChild(file.previewElement) : void 0;
        },

success: function(file, response) {
              //alert(response);
              $('#display_images').html(response);
            },

error: function(file, response) {
                  alert(response);
       }

};

27th November, 2017

david001 started a new conversation Dropzone Js:response After Upload Success • 2 months ago

How can i get response after successful upload by dropzone js and Laravel

my upload code at view is:

create.blade.php

<form action="{{url('gallery/post')}}/{{$post->id}}" class="dropzone">
    {{ csrf_field() }}
  
</form>

Route:

    Route::get('gallery/{id}','[email protected]');
    Route::post('gallery/post/{id}','[email protected]');

controller:

public function upload($id)
    {
      
            $post = Post::find($id);
            return view('gallery.create',compact('post'));
      
    } 

    public function postUpload(Request $request,$id)
    {
         
        $destinationPath = 'images'; 
        $extension =  $request->file('file')->getClientOriginalExtension(); 
        $fileName = time() . '.' . $extension;
        $upload_success = $request->file('file')->move($destinationPath, $fileName); 

      
            $image = new Image;
            $image->filename = $fileName ;
            $image->post_id = $id;
            $image->save();
      }

    ```    



26th November, 2017

david001 left a reply on How To Solve It • 2 months ago

@SyedAbuthahir it won't work since i am in gallery/create page (according to yours) where is my upload form and i need to fetch all images in same page (gallery/create) below form.

25th November, 2017

david001 started a new conversation How To Solve It • 2 months ago

I need to fetch all images based on current url id :eg:localhost:8000/company/post/id using jquery.

public function upload($id)
    {
        $post= \App\Post::find($id);

        return view('gallery.create',compact('post'));
        
    }

  public function postUpload(Request $request,$id)
   {   
        $destinationPath = 'gallery'; 
        $extension =  $request->file('file')->getClientOriginalExtension(); 
        $fileName = time() . '.' . $extension;
        $upload_success = $request->file('file')->move($destinationPath, $fileName); 
            
            $image = new Image;
            $image->filename = $fileName ;
            $image->post_id = $id;
            $image->save();
    }

Route:

     Route::get('company/post/{id}','[email protected]');
     Route::post('images/post/{id}','[email protected]');

view:


<form action="{{url('image/post')}}/{{$post->id}}" enctype="multipart/form-data">
    {{ csrf_field() }}
  //.......
</form>



<div id="show">display all images here based on current post id in url</div>

//Note: i have upload form above and display div below on same page


<script type="text/javascript">

$(document).ready( function(){
$('#show').load('url that pull all images based on current upload id');
refresh();
});
 
function refresh()
{
    setTimeout( function() {
$('#show').fadeOut('slow').load('/url that pull all images based on current upload id').fadeIn('slow');
      refresh();
    }, 2000);
}
</script>

for example :my current upload id in browser is localhost::8000/company/post/id Based on this Id i need to fetch all images in show div using jquery above.

I think i need to make another method that returns all images based on current Post Id.But how to get current Id. in another method so that i call pull images based on that Id

david001 left a reply on How To Get Id From One Function To Next Function • 2 months ago

error: Missing argument 1 for App\Http\Controllers\PostController::getImagesOfLatestPost()

david001 left a reply on How To Get Id From One Function To Next Function • 2 months ago

I am not getting error but its not working

david001 left a reply on How To Get Id From One Function To Next Function • 2 months ago

i am getting error

Type error: Argument 1 passed to App\Http\Controllers\PostController::postUpload() must be an instance of Illuminate\Http\Request, none given, called in ...

david001 left a reply on How To Get Id From One Function To Next Function • 2 months ago

please make it clear

david001 started a new conversation How To Get Id From One Function To Next Function • 2 months ago

I need id of one function to next function .how can i do this please help me Here after successfully saving data to database i want to grab that post Id in next function.


    public function postUpload(Request $request,$id)
    {
        $input =  $request->all();
        $postId = $id;

 
        $destinationPath = 'gallery'; 
        $extension =  $request->file('file')->getClientOriginalExtension(); 
        $fileName = time() . '.' . $extension;
        $upload_success = $request->file('file')->move($destinationPath, $fileName); 

        if($upload_success){
            
            $user = Auth::user();
            $image = new Image;
            $image->filename = $fileName ;
            $image->post_id = $postId ;
         
            $user->images()->save($image);
          
           }

         return $postId; //i need this id for second function

    }

Second method


    public function getImagesOfLatestPost()//this is get Route
    {
        return $this->postUpload($id);//first function
  
    }

I am not gettingpostId, i want post id because i want to load latest images based on post id from database with jquery.

24th November, 2017

david001 started a new conversation How To Route And Data • 2 months ago

I want to display my posts as : http://localhost:8000/posts/creatorName/postSlug my route is:

Route::get('posts/{creator}/{slug}', '[email protected]');

Controller:

public function show($slug){
    $posts = Post::where('slug',$slug)->first();

}

view:

@foreach($posts as $post)
    //display post title and description here
@endforeach 
link
    <center>
                <a href="/posts/{{ $post->user->name }}/{{$post->slug  }}" class="btn btn-primary">Read More</a></center>

In model i have used relationship: a user can have many posts and all posts belongs to user

23rd November, 2017

david001 left a reply on Ajax Request Laravel 5.5 • 2 months ago

remove datatType : 'json', or make it as datatType : 'text',

david001 left a reply on Ajax Post Error • 2 months ago

chrome browser

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.