mercredi 31 mai 2017

Displaying A Laravel Collection in a blade template

I'm having issues displaying a collection in a blade template.

$comments = Comment::all();

return view('comments/index')->with(compact('comments'));

The code for the blade is:

@isset($comments)

@foreach($comments as $comment)
  <div>
    <p>
     <a href=""><</a>
   </p>
 </div>
    <hr>
 @endforeach
 @endisset

@empty($comments) 

<div>
   <p>There were no comments available.</p>
      

@endempty

But not sure how to get the data to render in the template. It just renders a blankpage.



via Chebli Mohamed

Issue with dates [ first of month ] php and Carbon

I have an issue comparing dates. When I want to know if a date (default php date) is between two Carbon dates. I get a difference in the first day of month.

$date = date("2017-05-01");
    $date2 = date("2017-05-31");
    $since = Carbon::now()->firstOfMonth();
    $to = Carbon::now()->lastOfMonth();//->subDay();//$now->lastOfMonth();
    $this->info('since '.$since);
    $this->info('to '.$to);
    $this->info('date '.$date);
    $this->info('date2 '.$date2);
    $this->info("-------------------");
    if($date>= $since && $date <= $to ){
        $this->info('date in');
    }else{
        $this->info('date out');
    }
    if($date2>= $since && $date2 <= $to ){
        $this->info('date2 in');
    }else{
        $this->info('date2 out');
    }

The output is:

since 2017-05-01 00:00:00
to 2017-05-31 00:00:00
date 2017-05-01
date2 2017-05-31
-------------------
date out
date2 in

I expect $date output be 'date in'. Whats wrong?



via Chebli Mohamed

Laravel query writing

I am developing a project in Laravel 5.4. I want to write a select, insert and update query in my model that should work for any table in database. I used to do this is Codeigniter and work fine there, but I don't know how to use it in Laravel.

Following is the code from a model file in Codeigniter

class General_Model extends CI_Model {

        public function fetch_CoustomQuery($sql){
        $query = $this->db->query($sql);
        return $query->result(); 

        }


        public function create_record($data, $tbl) 
        {
        $this->db->set($data);
        $this->db->insert($tbl);
        return ($this->db->affected_rows() != 1) ? FALSE : TRUE;
        }



        public function update_record($data, $tbl, $wher) 
        {
        $this->db->where($wher);
        $this->db->set($data);
        $this->db->update($tbl);
        }


        public function delete_record($tbl, $wher) 
        {
        $this->db->where($wher);
        $this->db->delete($tbl);         
        } 
}

It was very easy in Codeigniter. I only need to pass the parameters and worked fine. I want to write same queries in my model in Laravel. Please help



via Chebli Mohamed

How to apply a JS variable to a Laravel Form Action

I need to pass an AJAX variable into my view such that the form action executes correctly. Using Laravel 5.4. and my (abbreviated) view looks like this:

<div id="product_form"  class="form-horizontal">

    

    <div id="supplier_search" > </div>
    <div class=" form-group">
        <div class="col-sm-2  col-md-2"></div>
        <div class="col-sm-4 col-md-4"></div>
        <div class="col-sm-2 col-md-2"></div>
        <div class="col-sm-4 col-md-4"></div>
    </div>

My Ajax function is passing all the values into the form fields correctly, however I am struggling to get the product_id into the correct place in the action statement. Laravel expects to see a variable.

Ajax Code (abbreviated):

 select: function( event, ui ) {
        var product_id = ( ui.item.value );

        $.ajax({
            url: "product_fullsearch/"+product_id,
            dataType: "json",
            type:"GET",
            success: function (data) {
                $('#product_name').val(data[0].product_name);
                $('#product_id').val(data[0].product_id);
                $("#supplier_name").val(data[0].supplier_name);
                $("#supplier_id").val(data[0].supplier_id);
            }
        });//END AJAX

    } 

I saw this Pass JS variable to form action on SO and gave it a go, but I could not get it to work in a Laravel context.

What am I dong wrong ? Many thanks !



via Chebli Mohamed

Laravel use query result in controller function

here is a part of the function in my controller

    $res= Commande::where('idClient',$id)->where('created_at',$datejour)->where('adresse',$addr)->get();
    if($res->isEmpty())
    {...
    }
    else
    {
        try {
        $resultat =\DB::table('ligne_commandes')->insert(['idCom'=>$res->idCom,'nomChaussure'=>$nomChaussure,'marque'=>$marque,'couleur'=>$couleur,'quantite'=>'1','pointure'=>$point]);
        return redirect()->back()->withErrors('Vous serez livrée dans un délai de 48 heures');
        }

        catch (\Illuminate\Database\QueryException $e) {
        return redirect()->back();

        }
    }

}

when i try to use $res->idCom, i got this error Property [idCom] does not exist on this collection instance. can someone help me?



via Chebli Mohamed

Issues with saving an image with an article

I'm pretty sure this is a noob question, even though I'm used to PHP, but not to Laravel

My goal can't be any more simple, I'd like to be able to write an article and add an image to it, but even though I made the upload system work (that wasn't a piece of cake), I'm having issues with saving the filename itself.

Here's how I proceeded:

use App\Photo;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

public function store(Request $request)
{

    $file = $request->file('image');
    $originalname = $file->getClientOriginalName();
    $path = 'uploads/' . $originalname;
    Image::make($file)->save($path);

    $product = new Photo(array(
        'name' => $request->get('name'),
        'image' => $originalname
    ));

    $product->save();

    return \Redirect::route('photo.index', array($product->id))->with('message', 'Product added!');
}

And here is my migration file, if this can help:

public function up()
{
    Schema::create('photos', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('image');
        $table->timestamps();
    });
}

So I wanted to save the filename as a string inside the database so I could call it later, like with $product->image, however I'm getting the following error:

SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `photos` (`name`, `updated_at`, `created_at`) values (sisdjfposd, 2017-05-31 22:42:18, 2017-05-31 22:42:18))

So I know what it means, and I don't like it because it was supposed to have a value: if I add die($originalname);before the line $product = new Photo array(, i get my filename so logically the variable isn't empty.

So why would I have this error? Am i missing something?

Thank you in advance



via Chebli Mohamed

Laravel Dispatch Job - check if dispatched?

I am using Amazon SQS driver for Laravel Queue Job.

I want to inform the user that the job has been dispatched in the Queue. How do I check this before returning response to the user?

For example:

dispatch(new UploadJob($request->all()));

return $this->respond(['status' => 'In Queued']); // Is it really in queue?



via Chebli Mohamed

Using Imagick with Laravel

I need to use Imagick in a Laravel project to convert an SVG to a PNG.

So far I have been unable to get it to work, Laravel keeps getting an error.

use Imagick;

in a function:

$image = new Imagick();

leads to

FatalThrowableError: Class 'Imagick' not found

We made sure that the extension is installed on the server, running

extension_loaded('imagick')

returns true.

What are we missing?



via Chebli Mohamed

Formatting XML for Twilio Response

I am attempting to receive a fax in my Laravel app, but I can't seem to format the XML properly.

Since I am just setting this up for the first time, I tried to emulate the basic how-to in the Twilio Quickstart guide.

Using the Twilio dashboard, I have set a webhook address of myapp.com/fax/sent to be notified when an incoming fax is attempting to be sent:

public function sent()
{
    $twimlResponse = new SimpleXMLElement("<Response></Response>");
    $recieveEl = $twimlResponse->addChild('Receive');
    $receiveEl->addAttribute('action', '/fax/received');

    return response($twimlResponse->asXML())
           ->header('Content-Type', 'text/xml');
}

The error that I get from Twilio is essentially empty:

Error 12100 Document parse failure

The Twilio error request inspector shows no head or body.

I have also tried to return a hard-coded view file in place of building the xml:

view fax.sent:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
   <Receive action="/fax/received" />
</Response>

and then changed the sent function to:

public function sent()
   {
      return View::make('fax.sent')->header('Content-Type', 'text/xml');
   }

This returns the same error message.



via Chebli Mohamed

Laravel Authentication using multiple Tables

I am new to Laravel. My application has below tables description

Users

+-----------------+------------------+------+-----+---------+----------------+
| Field           | Type             | Null | Key | Default | Extra          |
+-----------------+------------------+------+-----+---------+----------------+
| id              | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| email           | varchar(100)     | NO   | UNI | NULL    |                |
| first_name      | varchar(100)     | NO   |     | NULL    |                |
| last_name       | varchar(100)     | YES  |     | NULL    |                |
| profile_pic     | text             | YES  |     | NULL    |                |
| about           | text             | YES  |     | NULL    |                |
| alternate_email | varchar(200)     | YES  |     | NULL    |                |
| username        | varchar(70)      | NO   | UNI | NULL    |                |
| suspended       | tinyint(4)       | NO   |     | 0       |                |
| verified        | tinyint(4)       | NO   |     | 0       |                |
| remember_token  | varchar(100)     | YES  |     | NULL    |                |
| created_at      | int(11)          | NO   |     | NULL    |                |
| updated_at      | int(11)          | YES  |     | NULL    |                |
| deleted_at      | int(11)          | YES  |     | NULL    |                |
+-----------------+------------------+------+-----+---------+----------------+

The other table is UsersLogin:

+-----------------------+------------------+------+-----+---------+----------------+
| Field                 | Type             | Null | Key | Default | Extra          |
+-----------------------+------------------+------+-----+---------+----------------+
| id                    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id               | int(10) unsigned | NO   | MUL | NULL    |                |
| password              | text             | NO   |     | NULL    |                |
| password_salt         | text             | NO   |     | NULL    |                |
| password_salt_expiry  | int(11)          | NO   |     | NULL    |                |
| last_login            | int(11)          | NO   |     | NULL    |                |
| forgot_pass_key       | text             | YES  |     | NULL    |                |
| forgot_pass_expiry    | int(11)          | YES  |     | NULL    |                |
| forgot_pass_link_at   | int(11)          | YES  |     | NULL    |                |
| password_reset_at     | int(11)          | YES  |     | NULL    |                |
| signup_auth_key       | text             | YES  |     | NULL    |                |
| signup_auth_expiry    | int(11)          | YES  |     | NULL    |                |
| signup_verified_at    | int(11)          | YES  |     | NULL    |                |
| signup_verify_link_at | int(11)          | YES  |     | NULL    |                |
| created_at            | int(11)          | NO   |     | NULL    |                |
| updated_at            | int(11)          | YES  |     | NULL    |                |
+-----------------------+------------------+------+-----+---------+----------------+

Now as you can see, I have username and passwords in two differnet tables. I need to create a login with this table structure.

How should I implement my Auth facade to achieve this?



via Chebli Mohamed

Php Laravel Check If User Has Attribute Middleware

I need to check if a user has been accepted into the application (not simply authenticated) before allowing them access into a route group.

I have a middleware for this:

 public function handle($request, Closure $next)
    {
        if(!$request->user()->applicationAccepted() ){
            return redirect('/application/status');
        }
        return $next($request);
    }

My problem is I want administrators, who don't have applications to accept, to be allowed into this section. That is, they shouldn't see application/status.

My user model:

public function application()
    {
        return $this->hasOne('App\Models\Application','user_id');
    }

    public function applicationAccepted()
    {

    if($this->isAdmin){ //adminscansneakbywithoutapplications
        return true;
    }

        return $this->application->accepted;
    }

    public function isAdmin(){
        return $this->hasOne('App\Models\Admin','user_id');
    }

My problem is applicationAccepted() always stops the admins, even those who do have a isAdmin() relation. What is the proper way to query this hasOne relation within the very same user model?

Thank you.



via Chebli Mohamed

Working with laravel 5 notification

Have gone through laravel 5.4 doc on database notifications but there is little example on how to use it in your app and there are scanty information about it on Search Engine.

I would love to have a little more explanation on how to use it, with some examples.



via Chebli Mohamed

How to integrate other pages into laravel pre-built authentication

After reading some tutorials on laravel 5.4 authentication (including the doc),I don't know how to work with it in my file. I have been able to run the artisan command.. php artisan make:auth. Have seen the the controller, views etc that was created and even have accessed it by going to http://localhost/blogsite/public/register (don't worry about, its on my local disk) but how do I integrate it with with the pages that needs authentication? That I don't know..

Who can put me through how to integrate it with other pages



via Chebli Mohamed

Exception: Undefined offset: 0 while making a get request in laravel 5.4

getting Exception: Undefined offset: 0 while making a get request in laravel 5.4.

Not sure how to catch full error, i am pasting my code below:

ROUTE: Route::get('/merchants/create', function() { echo 'hellow'; });

instead of echoing hello

Exception: Undefined offset: 0



via Chebli Mohamed

Laravel crash on init with error 500 (no additional info)

I have some problems with deploying app to a shared host.

What i did till now:

  • copy all public files to public_html/website/my-api
  • copy all laravel system files to public_html/laravel
  • checked rights
  • corrected my-api/index.php require and require_once to a laravel/bootstrap/autoload.php
  • laravel logs are empty no data in
  • apache logs are empty no data in
  • my webhosting is Hetzner hosting

After some debugging it crashes here:

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

I get Error 500 and no other information. I double checked right etc. they are 777. It's just crash with error 500.



via Chebli Mohamed

Laravel $app in index.php is bool value

My main goal is to transfer laravel from my localhost to online shared hosting.

What i did till now:

  • copy all public files to public_html/website/my-api
  • copy all laravel system files to public_html/laravel
  • checked rights
  • corrected my-api/index.php require and require_once to a laravel/bootstrap/autoload.php

But error i am getting is

Fatal error: Call to a member function make() on boolean in /usr/www/users/baller/public_html/my-api/index.php on line 54



via Chebli Mohamed

Submit laravel form after Authentication

i have a modal form with tabs, i use ajax in submitting the form which work fine. I want the form should be public, if the user is not login it should display login and submit the form after logging in using ajax and laravel



via Chebli Mohamed

Deploy laravel ovh git composer in preprod and production env

I have a mutual server on OVH with an ssh key. I use laravel 5 for backend api and angularjs in front. I would like to deploy in my server 2 environment production(client)/preproduction(for test restricted by ip with htaccess). Wich is the best solution to do that with git and composer:

1st proposition: structure repository in my server :

bin/composer
depot_git/hooks/post-receive
 - MASTER
 - DEVELOP
Production (branch MASTER)
 - app  
 - bootstrap
 - config
 - config 
 - database
 - public 
 - ...
Preproduction (branch DEVELOP)
 - app      
 - bootstrap
 - config
 - config 
 - database
 - public 
 - ...

2nd proposition: structure repository in my server :

bin/composer
depot_git/hooks/post-receive
www/Production (branch MASTER)
 - app  
 - bootstrap
 - config
 - config 
 - database
 - public 
 - ...
www/Preproduction (branch DEVELOP)
 - app      
 - bootstrap
 - config
 - config 
 - database
 - public 
 - ...

I really would like to use the first proposition, what do you think? Do you have any other idea?

I need to have finally :

  • www.domain.com -> Production/public

  • http://ift.tt/2sdDiYC -> Preproduction/public

How can I do that? DNS?



via Chebli Mohamed

How do I save the oldvalue if the input name is variable?

The oldvalue is usually set with the name attribute, in my case the name attribute is variable depending on the id name="option", so I can't find the way to save and load the olvalue, this is my code:

<div class="btn-group" data-toggle="buttons">
   <label class="btn btn-primary">
     <input type="radio" name="option" id="question" autocomplete="off" value="1" data-oldvalue=""> Yes
   </label>
   <label class="btn btn-primary">
     <input type="radio" name="option" id="question" autocomplete="off" value="0" data-oldvalue=""> No
   </label>
</div>

Not sure if the autocomplete="off" will affect my oldvalue to load too. If there is any other approach to get my oldvalues loaded (after validation errors) I would like to know.

Extra info: I usually have between 3 and 5 questions loaded in the view. These questions are part of a poll I'm saving in the controller one by one with a foreach method



via Chebli Mohamed

How to decode and save multiple images sent as base64 string array to server directory?

I am writing a webservice for android app. From the mobile I am sending the image(s) which needs to be decoded and saved as jpg/jpeg/png (any one) format.

The data that will be sent will be a array of base64 which I need to handle it at the backend and save it into a server directory for future references.

To save image my code looks like this. (This is just a test method)

public function testing(Request $request){
    $i=0;
    foreach($request['images'] as $name)
    {
        $i +=1;

        $imagename= 'Image'.$i.'.jpeg';
        $destinationPath = public_path('images');
        $path = 'images/'.$imagename;
        $res = file_put_contents($path, base64_decode($name));
    }
}

This code will create an image with jpeg extension however when I try to open its just giving me this: enter image description here

I think I am missing something.

[Above code is just a demo of uploading a correct file from app.]



via Chebli Mohamed

Laravel Session::forget Method alters my JSON Get Request Output

I'm currently storing and retrieving data through angular requests that puts and retrieves values from a Laravel Session Array.

// Code for pushing into Laravel Session Array
Session::push('cart', $object); 

// Code for retrieving data into Laravel Session Array
return Session::get('cart'); 

Now i'm using a foreach loop to update quantity or where this question is about: To remove an object from the Laravel Session Array Cart when quantity is 0.

foreach ($cart as $index => &$product) {
            if ($product['id'] == $id) {
                if($operator == '+'){
                    $product['quantity'] = $product['quantity'] + $quantity;
                } else if($operator == '-'){
                    $product['quantity'] = $product['quantity'] - $quantity;
                    if($product['quantity'] == 0){ 
                        Session::forget('cart.' . $index);
                        $cart = Session::get('cart', []);
                        Session::push('cart', $cart);
                    }
                }
                Session::set('cart', $cart);
                $this->new_product = false;
                break;
            }
        }

This part of the code above is altering my JSON output:

Session::forget('cart.' . $index);
$cart = Session::get('cart', []);
Session::push('cart', $cart);

JSON Situation Before Deleting:

[
  {
   "id":293,
   "quantity":2
  },
  {
   "id":294,
   "quantity":2
  }
]

JSON Situation After Deleting:

{"1":{"id":293,
      "quantity":2}
}

But Should Be:

 [
  {
   "id":293,
   "quantity":2
  }
]

This is my JSON Get Request which simply calls: return Session::get('cart')

Cart.getCart()
   .then(function (success){
       $scope.cart = success.data;
    }).catch(function (e){
       console.log("got an error in the process", e);
    });

Any help would be appreciated. Not sure what is causing my json array to transform into a different data model.



via Chebli Mohamed

Pass php Laravel's APP_URL value to AngularJS

I use AngularJS in my Laravel app.

In AngularJS, I use:

$location.host()

to get the domain of my app (e.g: www.example.com) and get access to my API, e.g:

var url = $location.protocol() + "://" + $location.host() + "/api/products/" ;

Now I changed servers and my main app location went from www.example.com to www.example.com/here. $location.host() gives me www.example.com, but not the /here part.

I am trying to find a way to use Laravel's APP_URL value (which contains my main app location) and pass it to AngularJS:

var app = angular.module("appProducts"); 
app.controller("CtrlUserSchedule", ['$scope', '$http', '$location', '$modal', function($scope, $http, $location, $modal) {

    --> var laravelUrl = ** get php APP_URL value here **;

        var apiUrl = laravelUrl + "/api/products/" ;

What's the cleanest way to pass APP_URL to AngularJS. Is there a way to set it globally so APP_URL is available in all my AngularJS apps?



via Chebli Mohamed

Laravel - Php, display decoded JSON

I have decoded a JSON file and got:

array('data' => array('status' => 'ok', 'listings' => array(array('title' => 'Beauty and the Beast', 'times' => array('11:30')), array('title' => 'King Arthur - Legend of the Sword', 'times' => array('14:30', '20:45')), array('title' => 'Sing', 'times' => array('10:30')), array('title' => 'A Dog\'s Purpose', 'times' => array('10:20')), array('title' => 'The Boss Baby', 'times' => array('10:15', '12:45')), array('title' => 'Guardians of the Galaxy 2', 'times' => array('15:30', '17:30')), array('title' => 'Baywatch', 'times' => array('12:50', '15:50', '18:40', '20:30', '21:30')), array('title' => 'Pirates of the Caribbean: Salazar\'s Revenge', 'times' => array('11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00')), array('title' => 'Diary Of A Wimpy Kid - The Long Haul', 'times' => array('10:45', '13:10', '15:30', '17:50')), array('title' => 'Alien - Covenant', 'times' => array('18:30', '21:20')), array('title' => 'Peppa Pig: My First Cinema Experience', 'times' => array('10:00')))), 'http_response_header' => array('HTTP/1.1 200 OK', 'Date: Wed, 31 May 2017 10:15:06 GMT', 'Server: Cowboy', 'X-Powered-By: Express', 'Access-Control-Allow-Origin: *', 'Access-Control-Allow-Methods: GET, POST', 'Access-Control-Allow-Headers: X-Requested-With, Content-Type', 'Content-Type: application/json; charset=utf-8', 'Content-Length: 787', 'Etag: W/"313-zKqUamxe+yaLdbSsP4oLzQ"', 'Via: 1.1 vegur', 'Connection: close')))

But how do I output that in a page using laravel controller? Of course I just want the actual title and times associated with it?



via Chebli Mohamed

laravel error cannot convert to string

I am using Laravel 5.2 and have a problem.

My code is;

$sts = STSMember::find($member_id)->join('rating', 's_t_s_members.member_id', '=', 'rating.member_id');

But I get the following error

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string'.

How to get member_id from two table?



via Chebli Mohamed

How to use Word Com Application in Laravel Controller?

I'm use Laravel 5.4, PHP 7.1 on XAMPP. In advance I will say that the PHPWord does not suit me. I Want use Com Application in Laravel controller:

namespace App\Http\Controllers;
use App\Library\NCLNameCaseRu;
use DB;

class TestController extends Controller {

    public function index() {


        $debtid = DB::select(
            "EXECUTE dbo.SP_JudgApplicationFl @DebtID = ?", array('38')
        );



        foreach ($debtid as $v) {
            print_r($v->AccountNumber);
            $word = new \COM("Word.Application", null, CP_UTF8);
            $word->Visible = 0;
            $word->Documents->Add("C:/xampp/htdocs/myfile.dotx");
        }

    }

}

But i get error

Class 'COM' not found

I successfully connected a class "NCLNameCaseRu" with composer autoload. But this i have specific folder with class. How can I do the same with COM application?



via Chebli Mohamed

Goutte Crawler convert JSON

http://ift.tt/2rDNRY0

This link gives me a json list of title and times that the cinema is playing that specific film. I want to get that information and convert it to string however how is that possible? I have used json_decode and it says that node list is empty.

Here's my code:

function odeon(){
    $client = new Client();
    $crawler = $client->request('GET', 'http://ift.tt/2rDNRY0');
    //print $crawler->text()."\n";
    json_decode($crawler);
    print_r($crawler);
}



via Chebli Mohamed

Laravel user can follow Comment, Category, Post etc

I wanted to implement a follow system where a User can follow Comment, Category, Post and more. I have tried using Laravel Polymorphic relations for this but could not wrap my head around it. If someone can guide me it will be great.

Here is what I have tried.

User Model

public function categories()
{
    return $this->morphedByMany(Category::class, 'followable', 'follows')->withTimestamps();
}

Category Model

public function followers()
{
    return $this->morphMany(Follow::class, 'followable');
}

Follow Model

public function followable()
{
    return $this->morphTo();
}

public function user()
{
    return $this->belongsTo(User::class);
}

Follow migration

Schema::create('follows', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->morphs('followable');
    $table->timestamps();
});

How can I get the all the categories, comments followed by a user. Also how I can get the Followers of a Cateogry or Commnets etc.

Please help.



via Chebli Mohamed

Pagination not working on AJAX call on Price and brand filters , pagination Always shows 12 pages

Here is the attached Code SearchController.php

http://ift.tt/2slaRav

and

search.blade.php

http://ift.tt/2rn7Hps



via Chebli Mohamed

Laravel 5.4 Show custom error message in login page

I modify the login function in Login controller using credentials function

protected function credentials(\Illuminate\Http\Request $request)
    {
        return ['email' => $request->email, 'password' => $request->password, 'status' => 1];
    }

although the function is work, but i need to return an error message to show that "Account is suspended" in login page if user's status not equal to 1.

How can i modify the error message?



via Chebli Mohamed

laravel/codeception : test if json response contains only certain keys

I have a json array coming from my api as response:

{
  "data": [
    {
      "id": 1,
      "name": "abc"
    }
}

I am using laravel for api and laravel-codeception for testing.

public function getAll(ApiTester $I)
    {
        $I->sendGET($this->endpoint);
    }

I have to test if the response contains only id and name key (not any other key)

I have found $I->seeResponseContainsJson(), but it checks if JSON is present or not. It does not check if JSON response contains only specified keys.

Thanks.



via Chebli Mohamed

How to add add multiple values to modell before save in Laravel?

I have a custom fuction to parse incoming emails and their attachements. Of course one email may contain multiple attachement.

I have this code:

public function parseEmail() {
    // read from stdin
    $fd = fopen("php://stdin", "r");
    $rawEmail = "";
    while (!feof($fd)) {
        $rawEmail .= fread($fd, 1024);
    }
    fclose($fd);
    $parser = new Parser();
    $parser->setText($rawEmail);

    $email = new Email;
    $email->to = $parser->getHeader('to');
    $email->from = $parser->getHeader('from');
    $email->subject = $parser->getHeader('subject');
    $email->body_text = $parser->getMessageBody('text');

    $attachments = $parser->getAttachments();
    $filesystem = new Filesystem;
    foreach ($attachments as $attachment) {
        $filesystem->put(public_path() . '/uploads/' . $attachment->getFilename(), $attachment->getContent());
        $email->attachement()->name = $attachment->getFilename();
    }
    $email->save();

}

Now this code can store only one attachement. But how can I update to store multiple attachements in model?



via Chebli Mohamed

Laravel 5.4 cannot get Post method from vue.js

I'm trying to make an user authentication using laravel as back-end and vue.js as front-end, and it happens that after adding the cors middleware, laravel still doesn't get the post requests from vue.js (it works for get requests).

I'm using passport for the authentication and on the console I get a 404 error... I implemented vue.resource, cors, and passport (since I have the tables generated on the database by it and the new routes that passport implements) as it should be done, yet if there is some code that I did not upload in here that might help to get the solution to this problem, please feel free to ask.

Here is the code of the vue components...

Main.js:

import Vue from 'vue'
import App from './App.vue'
import Router from './routes.js'

import VueResource from 'vue-resource'

Vue.use(VueResource)

new Vue({
    el: '#app',
    render: h => h(App),
    router: Router
})

App.vue:

<template>
  <div class="container" id="app">
    <bar></bar>
    <router-view></router-view>
  </div>
</template>

<script>
  import bar from './components/bar.vue'
  var App = {
      csrfToken: ""
  }
  export default {
    components: {
      'bar': bar,
    }
  }
</script>

<style>

...

</style>

login.vue (Here is the post method):

<template>
    <div class="container">

  <div class="row" id="pwd-container">
    <div class="col-md-4"></div>

    <div class="col-md-4">

      <section class="login-form">

        <form method="post" action=# role="login">
          <input v-model="email" type="email" name="email" placeholder="Email" required class="form-control input-lg" value="joestudent@gmail.com" />

          <input v-model="password" type="password" class="form-control input-lg" id="password" placeholder="Password" required="" />


          <div class="pwstrength_viewport_progress"></div>

          <!--type="submit"-->
          <button @click="login" type="submit" name="go" class="btn btn-lg btn-primary btn-block">Sign in</button>
          <div>
            <a href="#">Create account</a> or <a href="#">reset password</a>
          </div>

        </form>

        <div class="form-links">
          <a href="#">http://ift.tt/1AXr3ha;
        </div>
      </section>  
      </div>

      <div class="col-md-4"></div>


  </div>
</div>
</template>

<script>


    export default {
        data(){
            return {
                email: '',
                password: ''
            }
        },
        methods: {
            login(){
                var data = {
                    grant_type: 'password',
                    client_id: 2,
                    client_secret: '1NB8ybcjuc1nOp70uwhJ7KygaK0AdsUHzroQuH7M',
                    username: this.email,
                    password: this.password,
                    scope: ''
                }

                this.$http.post('http://localhost:8000/oauth/token', data)
                    .then(response =>{
                        console.log(response.data)
                    })
                    .catch(response =>{
                       // Error array
                    })


            }
        }
    }

</script>

<style>

</style>



via Chebli Mohamed

How to track every user database interaction in laravel 5?

If any login user access any service then I want to track all query run by this user.

Example:

if user1 login and want to delete his profile details. and user2 want to update profile details.

then i want to get data in table like below

user  |   user_id  |   service     |   query  
user1 |     1      | deleteProfile |   "DELETE FROM Users WHERE id=1"
user2 |     2      | updateProfile |   "UPDATE Users SET lastname='Thaper' WHERE id=2"

For doing so I have try to use activity log like antonioribeiro/tracker and laravel-activitylog etc but did not achieve my requirements

How Can I do this in Laravel 5.2 ?

I appreciate all response. thanks head.



via Chebli Mohamed

laravel request array empties when all required validation fields are satisfied ,

[![sample of html post sections , Controller][1]][1]

When one of my required fields criteria is not met It all works just fine and as it should it gives me an error about filling up that required filed but as I satisfy all of the required validation fields the request array becomes empty , and Laravel raises all required errors . PS : I did create a Request class to handle the requests but that didn't solve the problem .



via Chebli Mohamed

mardi 30 mai 2017

Why is Laravel Eloquent generating SQL without quotation marks?

I'm trying to run sudo php artisan migrate db:seed on my Laravel installation and getting the following error:

  [Illuminate\Database\QueryException]                                                                                                          
  Array to string conversion (SQL: insert into `sponsor_phones` (`phone_number`, `type`, `is_primary`, `sponsor_id`, `updated_at`, `created_at  
  `) values (247-216-6255 x4356, Home, 1, 101, 2017-05-30 23:31:59, 2017-05-30 23:31:59))                           

It seems that the SQL Eloquent is creating for seeding lacks quotation marks where they are neede. Adding quotations in the right places (below) allows it to run.

insert into 
`sponsor_phones` 
(`phone_number`,
 `type`, 
 `is_primary`, 
 `sponsor_id`, 
 `updated_at`, 
 `created_at`
 ) 
  values 
  (
  '(732) 540-9730', 
  'Busi', 
  0,
  51, 
  '2017-05-27 21:53:44', 
  '2017-05-27 21:53:44');

I'm not sure what's causing this error, and searching for reasons why Eloquent is not adding quotations seems to be failing to produce any useful results.

I've got a repository up so that you can take a look (and because as an open source project it needs one anyway.)



via Chebli Mohamed

Laravel auth middleware not working to download jpeg

First, it happens only in production, I'm using Cloudways with laravel stack (debian + nginx + apache + mysql).

In my local environment, everything works fine.

Every time I try to open the URL with the right parameters I got redirected to home/login, like if the middlewere had rejected.

The URL was supposed to download my image.

Routes/web.php:

Route::get('image/{name}', 'FileController@getImage');

Controller/FileController.php:

class FileController extends Controller {
    public function __construct()
    {
        // if I comment this line, it works in production too, but I can download content without being logged in... 
        $this->middleware('auth');
    }

    public function getImage($name)
    {
        return response()->download(storage_path('app/images/' . $name), null, [], null);
    }
}



via Chebli Mohamed

Laravel Passing Controller data to View

Trying to pass data generated in controller to view.

Route in web.php

Route::get('person', ['uses'=>'PersonController@index']);

Controller app/Http/Controllers/Person.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class PersonController extends Controller
{
  public function index()
  {

    $age = 35;
    $height = 68;
    $weight = 102;

    // Calculate rest of BPX values
    $BPXVals = [];
    // Actual Weight
    $BPXVals['actualWeight']          =   $weight;
    $BPXVals['actualWeight2']         =   pow($weight, 2);
    $BPXVals['actualWeight3']         =   pow($weight, 3);
    $BPXVals['weightLN']              =   log($weight);

    return View::make('person.index', ['BPXVals'=>$BPXVals]);

  }
}

View in Resources/Views/index.php

<!doctype html>
<html>
    <head>
    </head>
    <body>
      
    </body>
</html>

Getting the following error:

ReflectionException in Container.php line 721:
Class App\Http\Controllers\PersonController does not exist

What am I doing wrong in defining my route or linking the route to the controller and/or view?



via Chebli Mohamed

Laravel 5: Redirect Not Working on Password Reset

I am trying to override Laravel's default function for resetting passwords. Before I go ahead with resetting the password, I want to dynamically set $redirectTo based on certain user information, so that the user is properly redirected to a different page based on said info. However, when I go try to go through with it I end up at a completely white page with the path ".../password/reset". The user's password is being properly reset, but the redirect isn't working as intended.

My code is referenced below. What am I doing wrong?

ResetPasswordController.php

class ResetPasswordController extends Controller
    {

        use ResetsPasswords;

        protected $redirectTo;

        public function __construct()
        {
                $this->middleware('guest');
        }

        public function resetPasswordByUser(Request $request, Users $users)
        {
                $user = $users->findUserByEmail($request->input('email'));

                if ($user->case == 1) {
                    $this->redirectTo = '/case1';
                } elseif ($user->case == 2) {
                    $this->redirectTo = '/case2';
                } elseif ($user->case == 3) {
                    $this->redirectTo = '/case3';
                }

                $this->reset($request);

            }
    }

web.php

Auth::routes();

.......

Route::post('/password/reset', 'Auth\ResetPasswordController@resetPasswordByUser');



via Chebli Mohamed

Undo minify js after running gulp --production

My question is, I want to minify my js from my laravel project i'm using elixir, I know that if I run gulp --production it will minify my js.

What I want to know is if i decide i need to edit my js, how can i unminify the js folder, is that even possible.

I haven't minified my js yet for fear that I might not be able to undo it.

At the moment all my js is being concatenated into one file called all.js , my understanding is that if i run gulp --production , then all the javascript in that file will now be minified, if that is true, then how do i unminify it when i want to trouble shoot or edit some javascript



via Chebli Mohamed

Show Posts Based on Viewer Timezone in Laravel

I'm working on a site that is scheduled to show tutorials contents to a student at a specific time. I'm using Laravel Framework and Carbon package. I have two fields in the Lessons table. The date/time field and the debut_timezone field to show tutorials to a student based on the scheduled date and time. It's working fine cause I'm using the WHERE clause in Laravel Eloquent.

// For example: 
$lessons = Lesson::where('debut_date', Carbon::now())->get();

How can I use the timezone field so that it will only show tutorial to students based on their timezone. For example, Students on the East Coast can view their lessons 3 hours before students on the West Coast and so on. In this case, when we go global, students in Asia will be able to view their lesson hours before students in the U.S, and so forth.

Please help, please?



via Chebli Mohamed

How to return views upon Ajax requests in Laravel

Let me start off by saying I am a moderate at Laravel/JQuery so please bear with my question.

I would like to return a view when the user clicks a button, using ajax. Whenever I click the button, I receive no error but also do not get any html. Any help is appreciated.

I defined my routes web.php as:

Route::get('ajax', function() {
    return view('test');
});

Route::post('/getmsg', function() {
     $msg = "<strong>This is a simple message.</strong>";
     $returnHTML=view('form1_sections/section2_form')->render();
     return response()->json(array('html'=>$returnHTML, 'msg'=>$msg));
});

My test.blade.php looks like:

<html>
<head>
    <meta name="csrf-token" content="">
    <title>Ajax Example</title>

    <script src = "http://ift.tt/1yCEpkO">
    </script>

    <script>
        function getMessage() {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                type: 'POST',
                url: '/getmsg',
                data: '_token = <?php echo csrf_token() ?>',
                success: function (data) {

                    $("#msg").html(data);
                }
            });
        }
    </script>
</head>

<body>
    <div id = 'msg'>This message will be replaced using Ajax. 
        Click the button to replace the message.</div>
    <form>
        <button onclick="getMessage()">Replace Message</button>
    </form>
</body>

My section2_form view looks like:

<div class="well">
<div class="row">
    <div class="col-xs-12">

        <h4>Date of Previous Research Leave</h4>
        <br>
        <label>Start Date:</label>
        <label>
            <input class="form-control" name="startDate" id="startDate" placeholder="Start Date" type="date">
        </label>
        <br><br>
        <label>End Date:</label>
        <label>
            <input class="form-control" name="endDate" id="endDate" placeholder="End Date" type="date">
        </label>
    </div>
</div>



via Chebli Mohamed

backpack-for-laravel pass query results to overwritten index

I want to pass the results of my query and display it on a custom view the way backpack list a model from a database.

this is my query result:(this should show 3 columns, name, station, parameter)

  $eq_parametro = Equipo::with('parametros')->with('estaciones')
                  ->buscarparametro($request->get('parametros'))
                  ->paginate(10);

to integrate on a custom view i need to override backpack index function on my controller

public function index()
{
$this->crud->hasAccessOrFail('list');

$this->data['crud'] = $this->crud;
$this->data['title'] = ucfirst($this->crud->entity_name_plural);

// get all entries if AJAX is not enabled
if (! $this->data['crud']->ajaxTable()) {
    $this->data['entries'] = $this->data['crud']->getEntries();
}

// load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
// $this->crud->getListView() returns 'list' by default, or 'list_ajax' if ajax was enabled
return view('your_view_name', $this->data);
}

how do i pass the query result to the function index and it shows a list of the 3 columns. need a real example.



via Chebli Mohamed

Laravel Guzzle getting destination and due time from a page

I want my website to scrape information from this page http://ift.tt/2rRckbS and in particular I want to scrape destination and due time from that website and give me an output.

At this moment my controller looks like this:

function guzzle(){
$client = new \GuzzleHttp\Client();
$results = $client->get('http://ift.tt/2riWRk3');
//$result->getBody();
//return view('hello')->with('results', $results);
//dd($result);
$results->getBody()->getContents();
dd($results);
return view('hello');
}

And the output is:

Response {#190 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:8 [▼
    "Content-Security-Policy" => array:1 [▶]
    "Content-Type" => array:1 [▶]
    "Date" => array:1 [▶]
    "ETag" => array:1 [▶]
    "X-Content-Security-Policy" => array:1 [▶]
    "X-WebKit-CSP" => array:1 [▶]
    "Content-Length" => array:1 [▶]
    "Connection" => array:1 [▶]
  ]
  -headerNames: array:8 [▼
    "content-security-policy" => "Content-Security-Policy"
    "content-type" => "Content-Type"
    "date" => "Date"
    "etag" => "ETag"
    "x-content-security-policy" => "X-Content-Security-Policy"
    "x-webkit-csp" => "X-WebKit-CSP"
    "content-length" => "Content-Length"
    "connection" => "Connection"
  ]
  -protocol: "1.1"
  -stream: Stream {#188 ▶}
}

However how can I access specific html class, scrape information from it and output it on my page?



via Chebli Mohamed

Laravel5, PHPUnit and Date Mutators: can't use mutator in data provider

I've just noticed that we can't use date mutators in a test data provider. Example

class FooTest extends TestCase {

    /**
     * @dataProvider baz
     */
    public function testBar($baz) {
        $this->assertTrue(true);
    }

    public function baz() {
        $model = new Foo(['someDate' => \Carbon\Carbon::now());
        return [
            [$model]
        ];
    }
}

Given your model like this

class Foo extends Model {

    public function getDates() {
        return ['someDate'];
    }

}

That test will produce the following error

PHP Fatal error:  Call to a member function connection() on null in /var/www/agents/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 3224

That's because in eloquent Model we have

protected function getDateFormat()
{
    return $this->dateFormat ?: $this->getConnection()->getQueryGrammar()->getDateFormat();
}

which is trying to access the connection that is not established in the test data provider.

So, how should we provide that testBar() method an input model?



via Chebli Mohamed

Laravel 5 Call to a member function createPlayer() on integer

I have a store procedure that creates a team for the logged in user like this:

public function store(Request $request)
{
    /**
     * Create Team
     */
    $this->validate($request, [
        'name' => 'required|min:3|max:255',
    ]);

    $team = Auth::user()->createTeam($request);

    /**
     * Create players
     */
    $players = [
        1   => 'ARQ',
        2   => 'DEF',
        3   => 'DEF',
        4   => 'DEF',
        5   => 'DEF',
        6   => 'MED',
        7   => 'MED',
        8   => 'MED',
        9   => 'ATA',
        10  => 'MED',
        11  => 'ATA',
        12  => 'ARQ',
        13  => 'DEF',
        14  => 'DEF',
        15  => 'MED',
        16  => 'MED',
        17  => 'MED',
        18  => 'ATA',
        19  => 'DEF',
        20  => 'ARQ',
        21  => 'DEF',
    ];

    foreach ($players as $num => $pos) {
        $player = $team->createPlayer($num, $pos);
    }

    $team->save();

    return redirect()->route('strategy');
}

and this works fine most of the time, but there are some times that it throws a Call to a member function createPlayer() on integer and can't replicate it, but the most weird part is that even when throwing the error the team and the players are created normally into the database. After refreshing the page everything continues as expected.

So, why could this error be appearing even when everything is working normally? How could the $team instance be getting changed into an integer?



via Chebli Mohamed

jquery php ajax insert data failed

I've tried to insert data from modal into database by ajax I'm using Laravel 5.3 I can't enter the data even when I console val is good but no passing into db notice there is relationships between database:may make difference modal code

<div class="modal fade" tabindex="-1" role="dialog" id="edit-modal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Edit Post</h4>
            </div>
            <div class="modal-body">

                <form>
                    <div class="modal-body">
                        <label for="post-body">Edit the Post</label>

                        <table class="table table-bordered">
                            <thead>
                            <tr>


                                <th style="background-color: #e85657; color: #FFFFFF ; text-align: center">pages</th>
                                <th style="background-color: #ff6a06; color: #FFFFFF ; text-align: center">category</th>
                                <th style="background-color: #2c81ba; color: #FFFFFF ; text-align: center">author</th>
                                <th style="background-color: #0f7864; color: #FFFFFF ; text-align: center">book name</th>
                                <th style="background-color: #5d6d7e; color: #FFFFFF ; text-align: center">day</th>
                            </tr>
                            </thead>
                            <tbody>

                            <tr>



                                <td>
                                    <div class="input-group">
                                        <input type="text" id="page" name="page" class="form-control" placeholder="pages" aria-describedby="basic-addon1">
                                        <span class="input-group-addon" id="basic-addon1"><i class="fa fa-file-text" aria-hidden="true"></i></span>
                                    </div>
                                </td>
                                <td>
                                    <div  class="input-group">
                                        <select id="option-list1" name="cat_id">
                                            <option value="1" disabled selected> category </option>
                                            <option value=""></option>
                                        </select>
                                        <span class="input-group-addon" id="basic-addon1"><i class="fa fa-tags" aria-hidden="true"></i></span>
                                    </div>
                                </td>
                                <td>
                                    <div class="input-group">
                                        <input type="text" id="author" name="author" class="form-control" placeholder="author" aria-describedby="basic-addon1">
                                        <span class="input-group-addon" id="basic-addon1"><i class="fa fa-user" aria-hidden="true"></i></span>
                                    </div>
                                </td>
                                <td>

                                    <div class="input-group">
                                        <input type="text" id="book" name="book" class="form-control" placeholder="name" aria-describedby="basic-addon1">
                                        <span class="input-group-addon" id="basic-addon1"><i class="fa fa-book" aria-hidden="true"></i></span>
                                    </div>

                                </td>

                                <span class="input-group-addon" id="basic-addon1"><i class="fa fa-table" aria-hidden="true"></i></span>

                                <th>
                                    <div  class="input-group">
                                        <select id="option-list day" name="day">
                                            <option disabled selected> days</option>
                                            <option value="saturday">saturday</option>
                                            <option value="sunday">sunday</option>
                                            <option value="monday">monday</option>
                                            <option value="thursday">thursday</option>
                                            <option value="wenensday">wenensday</option>
                                            <option value="tuesday">tuesday</option>
                                            <option value="friday">friday</option>

                                        </select>
                                        <span class="input-group-addon" id="basic-addon1 basics"><i class="fa fa-table" aria-hidden="true"></i></span>


                                    </div>
                                </th>


                            </tr>


                            </tbody>

                        </table>

                    </div>
                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

javascript code

var urlSave = '';
var token = '';
var weekId = 0;

$(function () {
    $('#error').hide();
    $('.update_user_button').on('click', function (event) {
        event.preventDefault();
        //var token = $('input[name="_token"]').val();
         weekId = $(this).attr('data-weekid');
        var days = $('input[name="day"]').val();
        var book = $('input[name="book"]').val();
        var author = $('input[name="author"]').val();
        var page = $('input[name="page"]').val();
        var data = new FormData();
        data.append('_token', token);
        data.append('week_id', weekId);
        data.append('book_name', book);
        data.append('author', author);
        data.append('page', page);

        $('#edit-modal').modal();


        $('#modal-save').on('click', function () {
            $.ajax({
                method: 'POST',
                url:urlSave,
                data: {
                    week_id: weekId,
                    days: days,
                    book_name: book,
                    author: author,
                    page: page,
                    _token: token
                },
                success: function (data) {
                    $('#edit-modal').modal('hide');
                    alert('done');
                },
                error: function (data) {
                    var errors = data.responseJSON;
                    console.log(errors);
                }



            });
        });


    });
});

BookController code

public function addBook(Request $request)
{
    $message = 'There was an error';

    //validation

    $book = new Book();
    $book->week_id = $request['week_id'];
    $book->days = $request['day'];
    $book->book_name = $request['book'];
    $book->author = $request['author'];
    $book->page = $request['page'];
    if($request->user()->week()->book()->save($book)){
        $message = 'Post Successfully created';
    };


    //save posts to currently auth user


    return Response::json($book);



}



via Chebli Mohamed

Laravel: including header and footer files not working

I want to include the header and footer file in my index.blade.php. I put all my header content in header.blade.php file and footer content in footer.blade.php file. Following is my Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class GeneralController extends Controller
{


    public function header()
    {
        return view('header');
    }

     public function footer()
    {
        return view('footer');
    }

    public function index()
    {
        $this->header();
        return view('index');
        $this->footer();
    }   
}

I am calling the header function before loading the main content. and footer file after loading the main content. I was doing this in Codeigniter and it worked fine there. but it is not working in Laravel. Please Help.



via Chebli Mohamed

Laravel Class 'App\Http\Controllers\GuzzleHttp\Client' not found

I have a problem with using guzzle, I am getting:

FatalThrowable Error with class not being found.

First I did: composer require guzzlehttp/guzzle

and then in my controller I have added:

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

and at this moment controller loooks like this:

function guzzle()
{
    $client = new Client();
    $results = $client->get('http://ift.tt/2riWRk3');

    //$result->getBody();
    //return view('hello')->with('results', $results);
    //dd($result);

    $response = $results->send();

    dd($results->getBody());
    dd($response);

    return view('hello');
}

How can this issue be fixed



via Chebli Mohamed

Group by not working - Laravel 5.2

Group by is not working, may be because i am using mathematical expression in the select option. Kindly help.

select FLOOR(SUM(DATEDIFF(rd.checkin_date,rd.created_at))/COUNT(DATEDIFF(rd.checkin_date,rd.created_at))) AS names, 

COUNT(rd.id) as totbooking, SUM(DATEDIFF(rd.checkout_date,rd.checkin_date)) AS nights, round(SUM(CASE WHEN h.currency_id=151 THEN rd.total_cents WHEN h.currency_id!=151 THEN rd.total_cents/cur.exchange_rate ELSE 0 END)/100) AS revenue, round((round(SUM(CASE WHEN h.currency_id=151 THEN rd.total_cents WHEN h.currency_id!=151 THEN rd.total_cents/cur.exchange_rate ELSE 0 END)/100)) / (SUM(DATEDIFF(rd.checkout_date,rd.checkin_date)))) as adr, FLOOR((FLOOR(SUM(CASE WHEN h.currency_id=151 THEN rd.total_cents WHEN h.currency_id!=151 THEN rd.total_cents/cur.exchange_rate ELSE 0 END)/100)) / COUNT(rd.id)) as atp, FLOOR(SUM(DATEDIFF(rd.checkin_date,rd.created_at))/COUNT(DATEDIFF(rd.checkin_date,rd.created_at))) as leadtime, SUM(DATEDIFF(rd.checkout_date,rd.checkin_date)) / (COUNT(rd.id)) as alos, (SUM(DATEDIFF(rd.checkout_date,rd.checkin_date)) / (h.total_rooms * 31))*100 as share

from reservation_details as rd left join hotels as h on rd.hotel_id = h.id left join currencies as cur on cur.id = h.currency_id left join chains as c on c.id = h.chain_id where rd.status >= 50 and date(rd.created_at) >= "2017-04-30" and date(rd.created_at) <= "2017-05-30" GROUP BY names



via Chebli Mohamed

Carbon tests failing

So i have an Laravel Application in which we check if time has passed by comparing current time in user timezone against time expired datetime stored in database of course in same timezone. So this is my code.

Test code

$staff = Staff::find(1);
$carbon = Carbon::now($staff->user->timezone);
$carbon->subHour(1);
$staff->status_exp = $carbon->toDateTimeString();
$processor = new Processor($staff);
$status = $processor->isExpired();
$this->assertTrue($status);

Application Code. Class has property name staff which is used below.

 public function isExpired()
    {
        $now = Carbon::now($this->staff->user->timezone);
        if($now->greaterThan(Carbon::parse($this->staff->status_exp)))
        {
            return true;
        }
        return false;
    }



via Chebli Mohamed

Laravel not found http exception

Hi I have a simple controller where I want to get content from a page using guzzle, however I am having trouble viewing any of the results because I keep getting error "NotFoundHttpException"

My route:

Route::get('hello', 'GuzzleController@test');

Controller:

function test(){
    $client = new GuzzleHttp\Client();
    $res = $client->get('http://ift.tt/N8YLMI', ['auth' =>  ['user', 'pass']]);
    echo $res->getStatusCode(); // 200
    echo $res->getBody(); // { "type": "User", ....
    return view('hello');
}

view:

{!! $res !!}



via Chebli Mohamed

Table record saving as string when it should be double

Could some explain why Laravel 5 is saving my decimal table record as string?

$table->decimal('bar', 5, 2)->nullable();

Seeder:

[...] // shorten to show what was created
'bar' => 10.5,

Tinker:

App\Foo::find(1)->bar //= "10.5"

I have no issues with integer but issues with double, float



via Chebli Mohamed

Get Database notification id in push notification

I am using database notification along with GCM and APN push notifications to send notifications.

My requirement is to mark the notification read, if a user clicks on the push notification in mobile. But only one notification need to be get updated, so the database notification id need to be passed in push notification. Is there any way to do this?



via Chebli Mohamed

Laravel 5 Using guzzle to scrape data

I am trying to scrape data from http://ift.tt/2riWRk3 and insert it into my page.

This is my first time doing it and I got completely stuck:

Route::

Route::get('hello', 'GuzzleController@guzzle');

Controller::

function guzzle(){
$client = new Client();
$results = $client->get('http://ift.tt/2riWRk3');
return $response->getBody();
}

What am I missing here?



via Chebli Mohamed

FCM_SENDER_ID or FCM_SERVER_KEY are invalid in laravel/brozot

I am new to FCM in laravel 5.2.

I am following this tutorial click here. But I am not able to send push notification. I have change the server and sender key in config/fcm.php but still it is throwing the error "FCM_SENDER_ID or FCM_SERVER_KEY are invalid".

Here I am using Api key as my server key and project number as sender Id.

        try {
    $optionBuilder = new OptionsBuilder();
    $optionBuilder->setTimeToLive(60*20);

    $notificationBuilder = new PayloadNotificationBuilder('my title');
    $notificationBuilder->setBody('Hello world')
                        ->setSound('default');

    $dataBuilder = new PayloadDataBuilder();
    $dataBuilder->addData(['a_data' => 'my_data']);

    $option = $optionBuilder->build();
    $notification = $notificationBuilder->build();
    $data = $dataBuilder->build();

    $token = "...";

    $downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
    print_r($downstreamResponse);die();

    $downstreamResponse->numberSuccess();
    $downstreamResponse->numberFailure();
    $downstreamResponse->numberModification();

    //return Array - you must remove all this tokens in your database
    $downstreamResponse->tokensToDelete(); 

    //return Array (key : oldToken, value : new token - you must change the token in your database )
    $downstreamResponse->tokensToModify(); 

    //return Array - you should try to resend the message to the tokens in the array
    $downstreamResponse->tokensToRetry();
}
    catch (\Exception $e) {
return $e->getMessage();

}

And my config/fcm.php

return [
'driver' => env('FCM_PROTOCOL', 'http'),
'log_enabled' => true,

'http' => [
    'server_key' => env('FCM_SERVER_KEY', '...'),
    'sender_id' => env('FCM_SENDER_ID', '....'),
    'server_send_url' => 'http://ift.tt/1TmHkUo',
    'server_group_url' => 'http://ift.tt/1mkLeNy',
    'timeout' => 30.0, // in second
],

];

Any help would be appreciated.



via Chebli Mohamed

Error while trying to show route:list in Laravel 5.4

I'am trying to use an API in laravel 5.4,and while executing in command-line 'php artisan route:list' to retreive all site routes, but unfortunately i get this error :

[ReflectionException] Class App\Http\Controllers\Api\V1\CausesController.php does not exist

this is my Controller :

namespace App\Http\Controllers\Api\V1;

use App\Cause;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreCausesRequest;
use App\Http\Requests\Admin\UpdateCausesRequest;
use App\Http\Controllers\Traits\FileUploadTrait;

class CausesController extends Controller
{
use FileUploadTrait;

public function index()
{
    return Cause::all();
}

}

and this is my api.php :

<?php

Route::group(['prefix' => '/v1', 'namespace' => 'Api\V1', 'as' =>    'api.'], function () {

Route::resource('causes', 'CausesController.php');

});

Thanks.



via Chebli Mohamed

remove double quote from array value - php

I have an array like below which comes from form:

array:4 [▼
  "login-history.view" => "true"
  "login-history.create" => "true"
  "login-history.edit" => "true"
  "login-history.delete" => "true"
]

I want to store it in database like this:

{
"login-history.view":true, //without double qoute in value true and false.
"login-history.create":true,
"login-history.edit":true,
"login-history.delete":true
}

But, when I saved it, it always saves like below:

{
"login-history.view":"true", //I want to remove double quote around true and false for every value 
"login-history.create":"true",
"login-history.edit":"true",
"login-history.delete":"true"
}

I want to save the record without double qoute around value(true and false). I currently simply saving the values as in eloquent value saving

$role = Sentinel::findRoleBySlug($slug);
$role->permissions = $permissions;
$role->save()

How can I achieve it?



via Chebli Mohamed

How to scrap / use API in Laravel

Is it possible to scrap content of the page using laravel?

How can you link an API in laravel app?

Here I have examples of content I need to scrap/API

Travel http://ift.tt/2riWRk3

Entertainment http://ift.tt/2sh7OA9 Oldham and Rochdale

News http://ift.tt/2riLiJI

Social https://dev.twitter.com/rest/public @smoke_yard read the posts and images.

If it is not possible using Laravel, how can you do it using any other technology like PvP or maybe JS?

Can you also explain to me what content to do I get back and how can I use it? is it a JSON or something else?



via Chebli Mohamed

Laravel Global Observer

I have a web application that is has around 50/60 different models, now what i want to do is create one main observer that I can pass in the model and the changes and store into a table....

I have a looked at some packages out there for example http://ift.tt/2qv9M3i

But i wont to make my own....

Could anyone point me in the right direction here?



via Chebli Mohamed

Laravel 5 PDOException Could Not Find Driver : sqlsrv

I could run the application, but when database connection needed, I got this error

PDOException in Connector.php line 55:
could not find driver
in Connector.php line 55
at PDO->__construct('sqlsrv:Server=192.168.5.43;Database=SSSPL', 'sssplwebuser', 'Welcome1', array('0', '2', '0', false)) in Connector.php line 55
at Connector->createConnection('sqlsrv:Server=192.168.5.43;Database=SSSPL', array('driver' => 'sqlsrv', 'host' => '192.168.5.43', 'database' => 'SSSPL', 'username' => 'sssplwebuser', 'password' => 'Welcome1', 'charset' => 'UTF8', 'prefix' => '', 'name' => 'sqlsrv'), array('0', '2', '0', false)) in SqlServerConnector.php line 32

How to fix it?



via Chebli Mohamed

Laravel Eloquent accessing fields from another table in scope

I have two tables:

  1. Users:

id, first_name, last_name, email


  1. Employees

id, user_id, wage

There has a relationship between users and employees. The problem comes from when I have a scope inside the model:

public function scopeSearchPaginateAndOrder($query) {
        $request = app()->make('request');

        return $query->whereHas('user.internal_companies', function ($company) {

              $company->where('companies.id', '=', \Session::get('current_company')['id']);

        })->where(function ($query) use ($request) {


      })->select(['user.first_name'])->get();
}

I am getting the following error:

Unknown column 'user.first_name' in 'field list

However, the relationship does exist:

public function user() {
        return $this->belongsTo('App\User', 'user_id');
    }



via Chebli Mohamed

Laravel 5 catching 400 response from PayPal API

I asked a very specific question located here: Laravel 5 catching PayPal PHP API 400 errors on localhost:8000

As nobody could help I want to make it a more open question about catching a 400 error from the PayPal API.

I am making requests to PayPal, when a successful request is made everything works perfectly and I get a lovely response object, which I can work with and action accordingly.

When for instance incorrect card details are entered Laravel throws a 400 error and fails to catch the error for me to action accordingly.

Snippet:

try {
    // ### Create Payment
    // Create a payment by posting to the APIService
    // using a valid ApiContext
    // The return object contains the status;

    $payment->create($this->_apiContext);

//will not catch here :( throws Laravel 400 error! want to redirect with message!
} catch (\PPConnectionException $ex) {
    return Redirect::back()->withErrors([$ex->getMessage() . PHP_EOL]);
}

//if we get an approved payment ! This fires perfectly when succesful!!! woo!!
if($payment->state == 'approved') {
    //if success we hit here fine!!!
} else {
    //won't get here, dies before catch.
}

Here is the error in Laravel debug mode:

enter image description here

When I look in the PayPal API sandbox logs I should be getting a nice object so I can action accordingly.

{
    "status": 400,
    "duration_time": 60,
    "body": {
        "message": "Invalid request. See details.",
        "information_link": "http://ift.tt/1c9EZc1",
        "details": [
            {
                "field": "payer.funding_instruments[0].credit_card.number",
                "issue": "Value is invalid."
            }
        ],
        "name": "VALIDATION_ERROR",
        "debug_id": "XXXXXXXXXXXXXX"
    },
    "additional_properties": {},
    "header": {
        "Date": "Thu, 25 May 2017 14:44:43 GMT",
        "paypal-debug-id": "2f88f18d519c3",
        "APPLICATION_ID": "APP-XXXXXXXXXXXX",
        "Content-Language": "*",
        "CALLER_ACCT_NUM": "XXXXXXXXXXXXX"
    }
}

If any Laravel wizard can help you would be my hero.

Nick.



via Chebli Mohamed

Why have Laravel Middleware contracts been deprecated?

I just discovered that Laravel 5.1 deprecated (and 5.2 removed) Middleware contracts. I used them for long time, but I have never noticed this removal.

Just a simple question, why?

Why do I have to define a method (handle) without any contract forces me to do this?



via Chebli Mohamed

Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz

I got this error

GuzzleHttp\Exception\ClientException: Client error: `POST http://ift.tt/2riapfS` resulted in a `400 BAD REQUEST` response:
{
  "message": "Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz (truncated...)

when i trying unit test for function i have ? how i can fix that ??



via Chebli Mohamed

could not find driver laravel sqlsrv

I have enabled sqlsrv and postgree extensions

Default connection is sqlsrv

.env configs

DB_CONNECTION=sqlsrv
DB_HOST=00.00.000.000
DB_PORT=1433
DB_DATABASE=DBNAME
DB_USERNAME=USER
DB_PASSWORD=5555555

Wrote following code for just checking is it working but the code thrown an error "could not find the driver"

Route::get('/',function (){
    dd(DB::connection()->getPdo());
    try {
        DB::connection()->getPdo();

        if(DB::connection()->getDatabaseName()){
            echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
        }
    } catch (\Exception $e) {
        die("Could not connect to the database.  Please check your configuration.");
    }
});

enter image description here



via Chebli Mohamed

composer require spatie/laravel-backup

I keep getting errors when I type composer require spatie/laravel-backup

Nessrines-MacBook-Pro-2:tfw nessrine$ composer require spatie/laravel-backup
Using version ^4.16 for spatie/laravel-backup ./composer.json has been updated
> php artisan clear-compiled
The compiled services file has been removed.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1 - Installation request for spatie/laravel-backup ^4.16 -> satisfiable by spatie/laravel-backup[4.16.0]. - Conclusion: remove spatie/db-dumper 1.5.1 - Conclusion: don't install spatie/db-dumper 1.5.1 - spatie/laravel-backup 4.16.0 requires spatie/db-dumper ^2.6 -> satisfiable by spatie/db-dumper[2.6.0, 2.6.1, 2.7.0]. - Can only install one of: spatie/db-dumper[2.6.0, 1.5.1]. - Can only install one of: spatie/db-dumper[2.6.1, 1.5.1]. - Can only install one of: spatie/db-dumper[2.7.0, 1.5.1]. - Installation request for spatie/db-dumper (locked at 1.5.1) -> satisfiable by spatie/db-dumper[1.5.1].
Installation failed, reverting ./composer.json to its original content. Nessrines-MacBook-Pro-2:tfw nessrine$ composer require spatie/laravel-backup’
enter image description here

via Chebli Mohamed

Laravel Validation - Using wildcard (*) in the error message

'attributes' => [
    'product_rate_.*.*' => 'Product .*. / .*.',
],

What i try to do is using wildcard(*) as variable in error message.

It shows like

Product . * . / . * . area is required.

I want to see a message like that.

Product 1 / 2 area is required.

How can i assign the * characters to variables and using them like @index1 and @index2 ?



via Chebli Mohamed

Timestamps in laravel is not working well

What happen to my created_at and updated_at fields? Im using laravel5.1. I have this on my table:

=====================================
Name               type               default
created_at   |   timestamp  |  0000-00-00 00:00:00
updated_at  |   timestamp  |  0000-00-00 00:00:00



Migration is this:

$table->increments('id')->unsigned();
$table->timestamps();


Result
The red is my actual date, the first green is the created_at and the second green is the updated_at enter image description here



via Chebli Mohamed

lundi 29 mai 2017

How to get the created_at in pivot table in laravel

Im confused how to get the created_at column in my pivot table. I have exam_user table with created_at and updated_at column. Now, I have this code in my view:

@if($exam->users()->where('user_id', Auth::user()->id)->exists())
    
    <div class="alert alert-success">You have done with this exam.</div>
@else

Any idea for this?



via Chebli Mohamed

Laravel correct way to bind data in raw sql string

I am using ? identifier for my DB::insert() and its working great, but I am having problem for my DB::select(), the ? doesn't work.

Here's my query:

    $result = DB::select("
        SELECT `department_code`, `name` FROM `tbl_departments` 
        WHERE `department_code` LIKE '%?%' OR `name` LIKE '%?%'
    ", [
        $searchkey, $searchkey
    ]);



via Chebli Mohamed

Save user data on click button

I'm working on laravel 5.4 and I have this code:

  public function apply($id){
        $user = User::where('id', $id)->get()->first();
        $data = [
          'name' => $user->first_name,
          'family' => $user->last_name,
          'email' => $user->email,
          'username' => $user->username,
          'gender' => $user->gender,
          'birthday' => $user->birthday,
          'cv' => $user->cv,
          'about' => $user->about,
          'education' => $user->education,
          'experiences' => $user->experiences,
        ];

        Mail::send('emails.apply', $data, function ($message) use ($company)
        {

            $message->from('noreply@gmail.com', 'Robert Nicjoo');
            $message->subject('New Apply');
            $message->to($company->email, 'Admin')

        });

        Session::flash('success', 'Your application was sent to company.');
        return redirect()->back()->with('session', $data);
  }

This will send email to company when user click on apply button and send user info to them, now I also want to save data of the user include user_id, ad_id and company_id in another table so both user and company owners can have access to their history of applied ads.

I also have this table to save data on:

  public function up()
    {
        Schema::create('applies', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('ad_id')->unsigned();
            $table->integer('company_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('ads', function($table) {
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('ad_id')->references('id')->on('ads');
            $table->foreign('company_id')->references('company_id')->on('ads');
        });
    }

but in my controller (first codes) I need to know how to save those information in new table (second codes)?



via Chebli Mohamed

database conection with laravel

Hi I'm developing an application with laravel 5.2, I'm triying to connect a remote database, if I do that in the command line I have to write this:

mysql -u root -p -h 'remote_ip' --skip-secure-auth

if I write that in the command line I don't have any problem. But I have to do the connection with laravel, how can I put the option

--skip-secure-auth on my database.php file

'estudiantesdb' => [
        'driver' => 'mysql',
        'host' => 'remote_ip',
        'port' => '3306',
        'database' => 'estudiantesdb',
        'username' => 'root',
        'password' => 'root_password',
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
    ],



via Chebli Mohamed

Laravel 5 Eloquent Relationship with Pivot Table

I have three tables:

  • Users (id, name, email)
  • Competitions (id, name, user_id)
  • Competitors (id, user_id, competition_id)

I wish to set up an eloquent relationship between the three tables. The competitors table is a pivot table for the other two tables. So far I have the following code, which allows me to list all competitions a user owns and allows me to add a competitor to a competition. However, I am struggling to get user details of all competitors in competition

class User {
  public function competitions() {
    return $this->hasMany(Competition::class);
  }
}

class Competition {
  public function join($user_id = 0) {
    $user_id = ($user_id == 0) ? \Auth::id() : (int)$user_id;

    $competitor = new Competitor(['user_id' => $user_id]);

    $this->competitors()->save($competitor);
  }

  public function users() {
    return $this->belongsTo(User::class);
  }

  public function competitors()
  {
    return $this->hasMany(Competitor::class);
  }
}

class Competitor {

}

What do I need to add to the relationships to return all competitors in a competition. Ideally I want to be able to do something likes this:

foreach($competition->competitors as $competitor) {
  echo $competitor->name.' '.$competitor->email; // etc
}



via Chebli Mohamed

Web app doesn't start - Displaying optimal route with Google JS API

first of all i am a beginner in programming. My question is why doesn't my web application start on submit.

I am using Google JavaScript API for calculating optimal route and i have been developing this web app in NetBeans with Laravel 5.

The goal of this application is to get locations from DB and display that locations on Google map and also to display the optimal driving route.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Waypoints in directions</title>
    <style>
      #right-panel {
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }

      #right-panel select, #right-panel input {
        font-size: 15px;
      }

      #right-panel select {
        width: 100%;
      }

      #right-panel i {
        font-size: 12px;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
        float: left;
        width: 70%;
        height: 100%;
      }
      #right-panel {
        margin: 20px;
        border-width: 2px;
        width: 20%;
        height: 400px;
        float: left;
        text-align: left;
        padding-top: 0;
      }
      #directions-panel {
        margin-top: 10px;
        background-color: #FFEE77;
        padding: 10px;
        overflow: scroll;
        height: 174px;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
   <div id="right-panel">
    <div>


    <br>
      <input type="submit" id="submit">
    </div>
    <div id="directions-panel"></div>
    </div>

   <?php

//$lokacije = locations, nar = is a table in db, Adresa = is a row (adress)
$lokacije = DB::table('nar')->pluck('Adresa');
echo json_encode($lokacije);

?>

    <script>

    var start = "Dolac 8, Rijeka";
    var end =  "Dolac 15, Rijeka";
    var lokacije = <?php echo json_encode($lokacije) ?>;
      function initMap() {
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          center: {lat: 45.328568, lng: 14.440477}  
        });
        directionsDisplay.setMap(map);

        document.getElementById('submit').onsubmit( function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        });
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  var waypts = [];
  var checkboxArray = lokacije;
  for (var i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected) {
      waypts.push({
        location: checkboxArray[i].value,
        stopover: true
      });
    }
  }
        directionsService.route({
          origin: start,
          destination: end,
          waypoints: waypts,
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
        }, function(response, status) {
          if (status === 'OK') {
            directionsDisplay.setDirections(response);
            var route = response.routes[0];
            var summaryPanel = document.getElementById('directions-panel');
            summaryPanel.innerHTML = '';
            // For each route, display summary information.
            for (var i = 0; i < route.legs.length; i++) {
              var routeSegment = i + 1;
              summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
                  '</b><br>';
              summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
              summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
              summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
            }
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
    </script>
    <script async defer
    src="http://ift.tt/2r5BfaE">
    </script>
  </body>
</html>



via Chebli Mohamed

paginate find if data returned is empty laravel 5.4 and display custom message

I recently added pagination in Laravel project. so I receive json data like this:

{"per_page":1,"current_page":1,"next_page_url":null,"prev_page_url":null,"from":null,"to":null,"data":[]}

before I use to get []

so my if condition use to be

@if($send_requests == '[]')

How can I check if data is empty in above json ?

I tried:

@if($send_requests->data == '[]')

it does not seem to work like that.



via Chebli Mohamed

Laravel 5 how to handle redirect when login with facebook / google on API?

When use Laravel Socialite package to login, there has an official method redirectToProvider

public function redirectToProvider('facebook')
{
  return Socialite::driver('facebook')->redirect();
}

If it serves as API, e.g, the route is /api/login/facebook, the response will have error Session store not set on request.

So how to send login request to provider when it is on API?



via Chebli Mohamed

How to store images for android/ios backend

I am trying to implement an api for my dummy mobile app and I am using MySQL and Laravel 5 for that. I want to store images that user posts from mobile client. I wonder, what is the best practice for storing this images. Any help would be appreciated.



via Chebli Mohamed

delete a user post using ajax and js in laravel 5.4

I'm new to Laravel. I am trying to create a common social network, Now i want to delete a user's post, After hitting the form it loads the ajax but can not delete the data. Here I gave my code. /My ajax code is:/

`$("#_global_modal").delegate('#modal_form_delete', 'submit', 
 function(event) 
 {

    // To stop a form default behaviour
    event.preventDefault();

    $.ajax({ 
       url: $(this).attr('action'),               
       type: $(this).attr('method'), 
       dataType: 'json',
       data: $(this).serialize(),
   })
    .done(function(response){
        if(response.delete == "success"){
            window.location.href = response.redirect_route
        }else{
            console.log(response);
        }
    })
    .fail(function(){
        console.log("error");
    })
    .always(function(){
        console.log("complete");
    });

});`

/*Route:*/
`Route::post('delete','crude@delete')->name('delete');`


/*
    `route_user_post        =   "";
    route_delete_post   =   "";`
*/

 /*My controller part:*/

 `public function delete(Request $request)

 {
    if($request->ajax()){
       $user = Auth::user();
       $user->post()->delete(['post' => $request->post]);

       return response()->json([
                'delete'            =>  'success',
                'redirect_route'    =>  route('profile')
            ]);

    }else{
        return response()->json([
            'delete'            =>  'ERROR',
            'ERROR_MSG'    =>  'ERROR MSG'
        ]);
        dd("Sorry you have to send your form information by using ajax 
      request");
    }
 }`

 /*So how can I solve this problem?*/



via Chebli Mohamed

laravel controller cannot use currentRouteName() inside construce()

I have named routes:
admin.post.category
admin.post.tag
admin.post.theme

routes\admin.php

Route::group(['prefix' => 'post', 'as' => 'post.'], function () {
    Route::resource('category', 'Admin\Post\TermsController');
    Route::resource('theme', 'Admin\Post\TermsController');
    Route::resource('tag', 'Admin\Post\TermsController');
});

Http\Controller\Admin\Post\TermsController

public function __construct(Request $request)
{
    $this->request = $request;

    $route_name = Route::currentRouteName();
    $arr = explode('.', $route_name);
    echo "<pre>".print_r($arr[2], 1)."</pre>"; exit;

}

When I visit the page http://localhost/admin/post/category, it can show category. But when I run command

php artisan route:list

It shows

  [ErrorException]
  Undefined offset: 2

If I move the three lines from __construct() to index()

$route_name = Route::currentRouteName();
$arr = explode('.', $route_name);
echo "<pre>".print_r($arr[2], 1)."</pre>"; exit;

Then "php artisan route:list" runs well.

How to fix this?



via Chebli Mohamed