lundi 30 juillet 2018

Retrieving media upload in controller from array dynamically

I am using Laravel 5.1 and I am using Illuminate\Http\Request instance for accessing sent file requests, but I can't seem to find the correct way to access the media element. I can access all other values in the object.

Here is the JSON data format I am using:

{"_method":"PUT",
"topic":"1 test",
"description":"1 test",
"media_description":"1 test",
"old_parts":
  {"part-1":
    {"sub_header":"test 2",
     "text_field":"test 2 ",
     "article_id":"18",
     "media":{}},
  "part-2":
    {"sub_header":"test 3 ",
     "text_field":"test 3",
     "article_id":"18",
     "media":{}}
  },
"published":"1",
"media":{}
}

I access media in controller using two foreach loops, one loop is for database collection and other is for form content. I can use following method for accessing media elements.

if ($file = $request->file('media-' . $running_number)) {...} 

But it decreases readability by huge amount as I should name the fields f.e. as media-1, media-2, ... and not access them using foreach loop like I do with everything else.

So is there a way to access file with foreach loop variable?

f.e. something like this

foreach($input['old_parts'] as $old_part) { 

  if ($old_part->hasFile('media')) { ... }

}

If I use the lines I typed the function returns a FatalThrowableError : Call to a member function hasFile() on array.

Or should I just use something like

$request->file('old_parts[part-'.$x.'][media]');

To access the file input and use custom variable to count the index? The problem is just that I can't figure out how to go inside multiple levels in JSON using file, as either old_parts['..']['..'] and old_parts['part-1']->media don't seem to return anything (return null).



via Chebli Mohamed

mercredi 25 juillet 2018

PHPUnit hanging on first test of third testcase class

Running Laravel 5.1

I've got a couple of testcase classes, each one runs fine by itself but when I run them together, eg. >phpunit without a filter, it hangs on the first test of the final testcase class. (I implemented my own listener so I could see which suites where running.

It doesn't break or just stop, it just sits at the command line and I have to ctrl C to stop the batch file. If I remove the first test case in the 3rd suite, it hangs on the next test.

I put in the xml file and also run it with --stderr, to no avail.



via Chebli Mohamed

lundi 23 juillet 2018

Laravel 5.1 $request->file return null

I'm currently working on a simple form to let users upload a name and an image. Unfortunately, the $request->input('image') and Input::file('image') return null. If I do $request->string('image') the name of the file uploaded is returned. Can someone explain to me what I am doing wrong?

Form

{!! Form::open(['url' => 'categories']) !!}
    <div class="form-group">
        {!! Form::label('name', 'Naam') !!}
        {!! Form::text('name') !!}
    </div>
    <div class="form-group">
        {!! Form::file('image', null) !!}
    </div>
    {!! Form::submit('Create Category!', array('class' => 'btn btn-primary')) !!}
{!! Form::close() !!}

Controller function:

    public function store(Request $request)
    {
        $rules = [
            'name'       => 'required',
            'image'      => 'required'
        ];

        $validator = Validator::make(Input::all(), $rules);

        /**
        * Adding the code here also returns null../
        * 
        $file = $request->file('image');
        dd( $request->file('image'));
        * 
        */

        // process the login
        if ($validator->fails()) {
            return Redirect::to('categories/create')
                ->withErrors($validator)
                ->withInput(Input::except('password'));
        } else {

            $file = $request->file('image');
            dd( $request->file('image'));
            $destination = public_path() . '/img/';
            $name = Carbon::now()->toDateTimeString();
            $extension = $file->getClientOriginalExtension();
            $filename = $name . '.' . $extension;
            $file->move($destination, $filename);

            $category = new Category();
            $category->name       = Input::get('name');
            $category->file_path = $filename;
            $category->save();

            Session::flash('message', 'Successfully created Category!');
            return Redirect::to('categories');
        }

    }



via Chebli Mohamed

dimanche 22 juillet 2018

Wkhtml2pdf liberay resulation in Mac

everyone!

I am stocked in a problem for 2 months, I have tried many ways and searched many solutions. even none of them worked for me.

I have installed attendize (event ticketing system) everything goes well but when I want to register as an attendee to get event ticket it gives me the following error. Please click to the screenshot I am running the attendize system in my local computer I think the problem is with wkhtml2pdf library but how I can solve it. Please, anyone, help me. Thanks.



via Chebli Mohamed

samedi 21 juillet 2018

Load Eloquent Model Relationships Child Nodes in Laravel 5.1

I can't return $parent->child() | I get null;

Parent Model

class PrinterSetting extends Model
{
    protected $table = 'printer_settings';
    //fillables here
    protected $with = ['copies'];

    public function copies(){
        return $this->hasMany(\App\DB\PrinterCopy\PrinterCopy::class, 'printer_id');
    }

}

Child Model

class PrinterCopy extends Model
{
    protected $table = 'printer_copies';

    public function printer(){
        return $this->belongsTo(\App\DB\PrinterSetting\PrinterSetting::class, 'id', 'printer_id');
    }

}

Code in Controller:

$availablePrinters = $this->printerSetting->where('is_active', 1)->get();
foreach($availablePrinters as $availablePrinter)
{
   //working
   foreach($availablePrinter->copies() as $copy)
   {
   //Not working
   }
}

I can't find the reason why it's not working. I Tried to dump $availablePrinter->copies and it work, but ofcourse I can't insert it on foreach() loop. Please help.



via Chebli Mohamed

mercredi 11 juillet 2018

Laravel - validate only digits with fixed length and required space

I am writing a regular expression to validate a zip code, where it should have exactly a length of 6 characters, the first 3 characters are digits, the last 2 also, but the character 4 should be a space.
Here some examples:

  • "123456" is not valid because no space in character 4.
  • "123 45" is valid.
  • "123 4" is not valid because the length is 5 instead of 6.

    Here what I wrote:

    /^[0-9 ]{6,6}$/

It works fine, just in this code above, the space is not required (but it should be).



via Chebli Mohamed

vendredi 6 juillet 2018

Laravel search issue in relationship

I have search functionality in laravel

$product=ProductItem::where(function ($query)use($fromDate,$toDate){
            if($fromDate!= ''&& $toDate!=''){
                $query->whereBetween(DB::raw("DATE(purchased_date)"),[$fromDate,$toDate]);
            }
        })->with(['itemName'=>
            function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='item_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            }
        ,'itemBrand'=> function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='brand_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            },'itemModel'=>function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='item_model_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            },'vendor'=>function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='vendor_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            }])




            ->get();

the above code if i search for itemName then it will return all records with emtpy itemNames for other than search items enter image description here In the screenshot i have searched for itemName nargis but it returned other itemnames with empty itemName and also i tried whereHas nut if foreign key null then it wont return any records

 $product=ProductItem::where(function ($query)use($fromDate,$toDate){
            if($fromDate!= ''&& $toDate!=''){
                $query->whereBetween(DB::raw("DATE(purchased_date)"),[$fromDate,$toDate]);
            }
        })->with(['itemName','itemBrand','itemModel','vendor'])
            ->whereHas('itemName', function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='item_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            })
            ->whereHas('itemModel', function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='item_model_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            })
            ->whereHas('itemBrand', function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='brand_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            })
            ->whereHas('vendor', function($query) use($searchInput,$filterBy) {
                if($filterBy!='all'&&$filterBy=='vendor_name'&&$searchInput!=''){
                    $query->where($filterBy,'LIKE',"%{$searchInput}%");
                }

            })
            ->get();

Can any one help me how i can add search functionality in laravel relationship



via Chebli Mohamed

Laravel Method filter does not exist when updating 5.1 to 5.2

I am getting this error while updating Laravel 5.1 to 5.2.

BadMethodCallException in Macroable.php line 74: Method filter does not exist

any help ?



via Chebli Mohamed

jeudi 5 juillet 2018

laravel proplem with Model::with appended column

i try to add appended column with Model::with

$pitchChech =  Pitch::with(['prices'=>function ($query){
            $query->select('*',\DB::Raw("(select sum(HOUR(TIMEDIFF(valid_to ,valid_from))) from pitch_price as xpitch_price where pitch_id = pitch_price.pitch_id ) as x "))
            ->whereRaw(" x < ?",[24]);
        }])->get();
      dd($pitchChech);

and i have this output

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'x' in 'where clause'  

i can't understand what is the problem im using laravel 5.1 but i don't think there are problem with ut



via Chebli Mohamed

Laravel routes not working with subfolder

Using Laravel 5 migrated from 4.2 now laravel 5 is installed in subfolder "abc" do i have to write abc/warehouse for every route ? previously it was /warehouse. i want to use all existing routes like /warehouse inside subdirectory abc.

i am on localhost xampp with port 81. http://localhost:81/warehouse

any one here with quick solution



via Chebli Mohamed

mardi 3 juillet 2018

Laravel: display multi data in one row for every user

How I can display multi data in one row with foreign key by id user for example: I have users with multi ticket, i need to display for every user number of his tickets in one column.

enter image description here

this my controller

public function followticket()
{
    $data = DB::table('tickets')
        ->join('users', 'users.id', '=', 'tickets.user_id')
        ->select('users.*', 'tickets.*')->get();

    return view('Admin.suivi-tickest',compact('data'));
}



via Chebli Mohamed

Issue in retrieving the data after submission of the form in the same page in laravel

Kindly help me with this issue. Before submitting the form in a variable called "$data" I have the data as below:

{ "message": "Required parameter missing: domain-name", "status": "ERROR" }

And after submitting the value in the form, in the same variable called "$data", I have the below data.

 {"decksys.com":{"classkey":"domcno","status":"available"}}

Now I need to display the "decksys.com" and the status "available".Find below my code and kindly help me to solve this issue.

Controller Code:

  class AvailableController extends Controller
  {

     public function create(Request $request)
     {

        $domainname = Input::get('domainname');
        $tld = Input::get('tld');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, 'https://httpapi.com/api/domains/available.json?auth-userid=711757&api-key=74miSZPgYkkc108Ptmeo5Q8iDTtKk3xi&domain-name='.$domainname.'&tlds='.$tld.'');
        $result = curl_exec($ch);
        curl_close($ch);
        $data = json_encode($result);
        $response = json_decode($data);
       // $result = json_decode($response);
       $data = json_decode($response, true);

        return view('clientlayout.main.tld',compact('data'));

     }
    }

View Page:

     @foreach($data as $key => $value)

     @if ($data['status'] == 'ERROR')

       

     @endif


     @endforeach

Here it checks the status correctly and displays "ERROR". But after submitting the form I'm getting the error as: "Undefined index: status ". Kindly help me to solve this issue.



via Chebli Mohamed

lundi 2 juillet 2018

Laravel data filtering and sorting with pagination

I am developing a laravel project which has a function to search tournaments. it has a view to list all tournaments. then it has functionalities to search by id, name, category etc. i want to sort this list A-Z with filtered results also. how can I do that?table has over 1 million records.when i user orderBy('table.name','asc'), it takes a lot time. this query uses paginate as well.what would be the best practice to do this?



via Chebli Mohamed