mardi 31 octobre 2017

Laravel bootstrap a default Guzzle client

I would like to bootstrap a default Guzzle client to connect with Github. Currently I am setting up a default client in a controller like so:

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->client = new Client([
            'base_uri' => 'https://api.github.com',
            'headers' => [
                'Authorization' => 'token ' . $this->getAccessToken()
            ]
        ]);

        return $next($request);
    });
}

I am wrapping it with the middleware closure because otherwise the user that is currently logged in is not available yet. getAccessToken needs an Auth::user.

How would I rewrite this to a generic re-usable client though? Judging by the documentation from Laravel a good idea might be to bind a GithubGuzzleClient into the container through a ServiceProvider:

http://ift.tt/2z1320p

It seems like ServiceProviders are bound into the container before the middleware is even run though. So how would I set up a generic ServiceProvider that can also access the logged in user to set the proper Authorization header on the freshly instantiated client?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gZcnyO
via IFTTT

saving into 2D session in laravel

I'm trying to convert a pure PHP code to Laravel. This code works with session extensively - here is the simplified part of the code (please ignore syntax errors):

    $_SESSION['gamedata']=[
        'game'=> 23 ,
        'n'=>0,
        'Cards'=>[],
        'Values'=>[],
    ];
    $_SESSION['gamedata']['Cards'][]= getCard();
    $_SESSION['gamedata']['Values'][]= getVal();

right now based on the laravel documentation my option is

    session(['gamedata' =>  [
        'game'=> 23 ,
        'n'=>0,
        'Cards'=>[],
        'Values'=>[],
    ]]);

    $gamedata = session('gamedata');
    $gamedata['Cards'][]= getCard();
    session(['gamedata'=>$gamedata]);

    $gamedata = session('gamedata');
    $gamedata['Values'][]= getVal();
    session(['gamedata'=>$gamedata]);

which is very stupid ... and no i cant save it one at the end of the line becuz functions also work with session so session needs to be saved before each function call

basically i want to be able to save in 2d session instantly something like

session([ ['gamedata']['Cards'][] => getCards() ]);

which right now gives me this error

Cannot use [] for reading

even this code

session([ ['gamedata']['Cards'] => getCards() ]);

gives me this error

Undefined index: Cards



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2h0j049
via IFTTT

How reduce Redirect condition size in Laravel?

I'm trying to make things more simple in my Laravel application. Therefore I'm wondering how's it possible to NOT redirect the Client if one of my function returns true and how to redirect if it is a string (not true).

So let's say I have a function like this:

public function returnText() {
   $r = rand(1,100);
   if ($r > 50)
   {
     $redir = true;
   }
   else
   {
     $redir = 'http://google.com';
   }
   return $redir;
}

What I want within my Laravel's controller's function is to redirect the user if the result is an URL and don't redirect if it's simply 'true' (or anything basically it doesn't matter if I return true or something else).

Now I can obviously do that with a few lines but I'd like to optimize it only to take 1 max 2 lines.

public function redi() {
    return redirect(CustomFunction::returnText());
}

I've tried this approach but it obviously throws some error, because it can't understand 'true'.

Any ideas on how to achieve this with the least lines of code?

P.S.: using Laravel 5.5



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zleC7s
via IFTTT

Data not storing in the DB [Laravel 5.5]

I'm using Laravel 5.5. I wanted to store my data in the DB, but when i try to do it - nothing is happening. Here is my MarketController code

public function store(Request $request)
{


    $this->validate($request, [
        'name' => 'required|unique:markets|max:255',
        'website' => 'required',
        'city' => 'required',
    ]);
    Market::create($request->all());
    return redirect('markets'); 
}

My save.blade.php code

<!DOCTYPE html>
 <html>
 <head>
   <title>Create Market</title>
 </head>
 <body>
  @extends('layouts.app')
  @section('main')
  <form action="" method="post">
    
    <input type="hidden" name="_token" value="DaBSErIRWPPI">
    <label for="name">Name</label>
    <input type="text" name="name" id="name">
    <label for="city">Location</label>
    <input type="text" name="city" id="city">
    <label for="website">Market's website</label>
    <input type="text" name="website" id="website">
    <button type="submit"><a href="">Add Market</a>
</button>
</form>
</form>

And here is index.blade.php code

<h1><a href="">Add Market</a></h1>

Nothing happens. Please, help. Thank U!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lyprNj
via IFTTT

Keep getting 401 unauthorized 'invalid credentials' Laravel Passport

I have generated some demo user through seeders. I can login those user by oauth/token. But when i create new user i cant login anymore. It always giving me 401 unauthorized 'invalid credentials'. I have done all research. I am testing through POSTMAN I am totally clueless. this is my register method:

$user = new User;
$user->name = ucfirst($request['name']);
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
return response()->json('success'); 

Pls help me !!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xEZLjt
via IFTTT

Strtotime is not converting all dates?

I have a json response like this:

{
    "count": 9,
    "facebook": [
        {
            "description": "Calling all Fitness Instructors... Are you already thinking about your next course to study in 2018? Read on... We deliver courses that you can take away and teach the day after! We are proud of our specialist tutors and face to face training. Meet like minded fitness professionals, share ideas and network.",
            "time": "2017-10-29T12:22:47+0000",
            "image": "http://ift.tt/2A2LKha",
            "link": "http://ift.tt/2xGbLS3"
        },
        {
            "description": "Calling all Fitness Instructors... Are you already thinking about your next course to study in 2018? Read on... We deliver courses that you can take away and teach the day after! We are proud of our specialist tutors and face to face training. Meet like minded fitness professionals, share ideas and network.",
            "time": "2017-10-15T09:59:25+0000",
            "image": "http://ift.tt/2A2LKha",
            "link": "http://ift.tt/2xGbLS3"
        },
        {
            "description": "Really excited after our call with Fitness Professionals. Look out for our partnership with Fitpro very soon 🎉🎉🎉 this means discounts and offers for Trained Academy Graduates 🎓",
            "time": "2017-10-11T14:57:12+0000",
            "image": "http://ift.tt/2A2LKha",
            "link": "http://ift.tt/2xGbLS3"
        },
        {
            "description": "Really excited after our call with Fitness Professionals. Look out for our partnership with Fitpro very soon 🎉🎉🎉 this means discounts and offers for Trained Academy Graduates 🎓",
            "time": "2017-10-10T06:12:26+0000",
            "image": "http://ift.tt/2A2Q0x6",
            "link": "http://ift.tt/2xH9y8R"
        },
        {
            "description": "16-18? Jump into a #personaltraining #career! Started college and decided it’s not for you? \n\nWant to be a Gym Instructor? Circuit Trainer? 🏋🏻\nOr work towards a career in the Fire Service? 🔥 \n\nJoin us Weds night for open enrolment or careers advice from @paulalitherland and @nickyjanew  \n@mahdloyouthzone 6:30pm Wednesday 11th October. \n\nFully Funded for 16-18 year olds \nUCAS accredited \nIndustry recognised L2 Gym / L3 PT\nExclusive discounts using your Fire Team badge \nFree food box @chiaproteinbar \nWork placements @thegymgroup",
            "time": "2017-10-08T04:49:42+0000",
            "image": "http://ift.tt/2A3swIb",
            "link": "http://ift.tt/2xGbMW7"
        },
        {
            "description": "#trainedacademy #team @mahdloyouthzone preparing marketing material for 2018 enrolments. #oldhamfitness #oldham #practical #learningenhanced #alevels #employability @gymcareer @thegymgroup @chiaproteinbar",
            "time": "2017-10-06T07:48:20+0000",
            "image": "http://ift.tt/2A33o4y",
            "link": "http://ift.tt/2xGbNt9"
        },
        {
            "description": "Looking for an Exercise to Music Course? Our new tutor Becky Jackson can’t wait to set some dates. Let us know if you’re ready! 💕",
            "time": "2017-10-05T04:22:11+0000",
            "image": "http://ift.tt/2A33o4y",
            "link": "http://ift.tt/2xGbNt9"
        },
        {
            "description": "Looking for an Exercise to Music Course? Our new tutor Becky Jackson can’t wait to set some dates. Let us know if you’re ready! 💕",
            "time": "2017-10-04T06:05:44+0000",
            "image": "http://ift.tt/2A1NxD3",
            "link": "http://ift.tt/2xH9BBz"
        },
        {
            "description": "We are excited to launch our next teacher training qualification with the amazing Jeanette Smout. \n\nBook before 30th Oct as the price is wrong 🤦🏻‍♀️ should be £450 as it’s now 3 days face to face training. Could you be one of our future tutors?? 🤗",
            "time": "2017-10-04T05:57:14+0000",
            "image": "http://ift.tt/2A1NxD3",
            "link": "http://ift.tt/2xH9BBz"
        }
    ]
}

However, when I add date and strtotime like this:

   $date = date('l, jS F, Y h:ia', strtotime($rawDate));

Then result is like this:

{
    "count": 9,
    "facebook": [
        {
            "description": "Calling all Fitness Instructors... Are you already thinking about your next course to study in 2018? Read on... We deliver courses that you can take away and teach the day after! We are proud of our specialist tutors and face to face training. Meet like minded fitness professionals, share ideas and network.",
            "time": "Sunday 29th October 12:22pm",
            "image": "http://ift.tt/2A0HTRH",
            "link": "http://ift.tt/2xH9Dtb"
        },
        {
            "description": "Calling all Fitness Instructors... Are you already thinking about your next course to study in 2018? Read on... We deliver courses that you can take away and teach the day after! We are proud of our specialist tutors and face to face training. Meet like minded fitness professionals, share ideas and network.",
            "time": "2017-10-15T09:59:25+0000",
            "image": "http://ift.tt/2A0HTRH",
            "link": "http://ift.tt/2xH9Dtb"
        },
        {
            "description": "Really excited after our call with Fitness Professionals. Look out for our partnership with Fitpro very soon 🎉🎉🎉 this means discounts and offers for Trained Academy Graduates 🎓",
            "time": "Wednesday 11th October 03:57pm",
            "image": "http://ift.tt/2A0HTRH",
            "link": "http://ift.tt/2xH9Dtb"
        },
        {
            "description": "Really excited after our call with Fitness Professionals. Look out for our partnership with Fitpro very soon 🎉🎉🎉 this means discounts and offers for Trained Academy Graduates 🎓",
            "time": "2017-10-10T06:12:26+0000",
            "image": "http://ift.tt/2A2Q0x6",
            "link": "http://ift.tt/2xH9y8R"
        },
        {
            "description": "16-18? Jump into a #personaltraining #career! Started college and decided it’s not for you? \n\nWant to be a Gym Instructor? Circuit Trainer? 🏋🏻\nOr work towards a career in the Fire Service? 🔥 \n\nJoin us Weds night for open enrolment or careers advice from @paulalitherland and @nickyjanew  \n@mahdloyouthzone 6:30pm Wednesday 11th October. \n\nFully Funded for 16-18 year olds \nUCAS accredited \nIndustry recognised L2 Gym / L3 PT\nExclusive discounts using your Fire Team badge \nFree food box @chiaproteinbar \nWork placements @thegymgroup",
            "time": "Sunday 8th October 05:49am",
            "image": "http://ift.tt/2A3swIb",
            "link": "http://ift.tt/2xGbMW7"
        },
        {
            "description": "#trainedacademy #team @mahdloyouthzone preparing marketing material for 2018 enrolments. #oldhamfitness #oldham #practical #learningenhanced #alevels #employability @gymcareer @thegymgroup @chiaproteinbar",
            "time": "Friday 6th October 08:48am",
            "image": "http://ift.tt/2A33o4y",
            "link": "http://ift.tt/2xGbNt9"
        },
        {
            "description": "Looking for an Exercise to Music Course? Our new tutor Becky Jackson can’t wait to set some dates. Let us know if you’re ready! 💕",
            "time": "Thursday 5th October 05:22am",
            "image": "http://ift.tt/2A33o4y",
            "link": "http://ift.tt/2xGbNt9"
        },
        {
            "description": "Looking for an Exercise to Music Course? Our new tutor Becky Jackson can’t wait to set some dates. Let us know if you’re ready! 💕",
            "time": "2017-10-04T06:05:44+0000",
            "image": "http://ift.tt/2A1NxD3",
            "link": "http://ift.tt/2xH9BBz"
        },
        {
            "description": "We are excited to launch our next teacher training qualification with the amazing Jeanette Smout. \n\nBook before 30th Oct as the price is wrong 🤦🏻‍♀️ should be £450 as it’s now 3 days face to face training. Could you be one of our future tutors?? 🤗",
            "time": "Wednesday 4th October 06:57am",
            "image": "http://ift.tt/2A1NxD3",
            "link": "http://ift.tt/2xH9BBz"
        }
    ]
}

So as you can see above some of the date are not being converted to human readable dates, why is this happening? is there something wrong with my code? Or is that a problem with the JSON i am retrieving?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2A4mhnx
via IFTTT

anam-hossain/captcha working localy using valet but not on forge -> DigitalOcean droplet

I installed the captcha swiftly on my local computer where I use valet. When I deployed it to the server it does not work. It is just showing the text:

@captcha()

where the acctual captcha box shows on my local comp.

I did run composer install on the server and the package is required on the server and seem to be installed as I can find it in the vendor.

What can this be?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iOv9K3
via IFTTT

DOM Crawler selectLink when value inside

Hello i want to ask how to do selectLink()

example

<a href="/blog/category/security-advisories">Security Advisories</a>

$client = new Client(); 
$link = $crawler->selectLink('SecurityAdvisories')->link(); 
$crawler_download = $client->click($link);

but my problem is like this

<a href=" /naruto-shippuden-episode-5" class="">
<div class="name"> EP 5</div>
<div class="vien"></div>
<div class="cate">SUB</div>
</a>

here's my code and it says node list empty and cant use the ->click()

$crawler_episode_lists->filter('a .name')->each(function ($node, $i) {
    print($node->text(). "\n");
    $link = $crawler_episode_lists->filter('a .name')->link();
    $crawler_download = $get_episode_lists->click($link);
});

Anyone face problem like this ? Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iPH2iR
via IFTTT

laravel nginx different roots to different projects

I have global project (web wrapp) and multiple projects. Structure of files

project/
  application/
  index.php
    project1/
    project2(on laravel)/
      public/
        index.php

So, if i call project, i get index.php. I want to run project2/public/index.php with url /project2. nginx conf below:

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /home/user/projects/project/application;
  index index.php index.html index.htm;

  location /project2/ {
    root /home/user/projects/project/application/project2/public/;
    try_files $uri $uri/ /index.php$is_args$args;
  }

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.1-fpm.sock;
    fastcgi_read_timeout 600;
  }
}

With this configuration I get nginx's 404 when ask /project2. If I replase

location /project2/ {
  root /home/user/projects/project/application/project2/public/;
  try_files $uri $uri/ /index.php$is_args$args;
}

with

location /project2/ {
  root /home/user/projects/project/application/project2/public;
  try_files $uri $uri/ /project2/public/index.php$is_args$args;
}

I get Not found from Laravel. Is it possible to solve my problem?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gQ58Wc
via IFTTT

How to supply a different implementation if the class implements an interface using Laravel's container

I’m using dependency injection to inject instances of Guzzle’s HTTP client. I have several data provider classes that call external services, some of which needs to be routed through proxies. I have an empty interface ConnectViaProxy that is implemented on those classes. I want to bind a Guzzle instance with the proxy option set, but I can’t use:

$this->app->when(ConnectViaProxy::class)
    ->needs(GuzzleClient::class)
    ->give(function (): ProxiedGuzzle {
        return new ProxiedGuzzle();
    });

Because when requires a concrete class, not an interface.

Here is an example of a provider that should be proxied:

use GuzzleHttp\Client as GuzzleClient;

class FooProvider implements Provider, ConnectViaProxy
{
    public function __construct(GuzzleClient $client)
    {
        // Should be an instance of ProxiedGuzzle
        dd($client);
    }
}

And an example of a provider that shouldn't be proxied:

use GuzzleHttp\Client as GuzzleClient;

class BarProvider implements Provider
{
    public function __construct(GuzzleClient $client)
    {
        // Should be an instance of GuzzleClient
        dd($client);
    }
}

And here is the ProxiedGuzzle class:

use GuzzleHttp\Client as GuzzleClient;

class ProxiedGuzzle extends GuzzleClient
{
    public function __construct()
    {
        parent::__construct([
            'proxy' => [
                'http' => PROXY_IP,
                'https' => PROXY_IP,
            ],
        ]);
    }
}

Any idea how I could do this?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lxdjfy
via IFTTT

not show link prewiew in telegram open meta data

I,m using open graph meta tags and when share links has og meta tags not correct working in Telegram. like link: http://ift.tt/2A2q3he



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yhGkSs
via IFTTT

Laravel 5 if statement between Carbon diffForHumans and toFormattedDatesString

I want to write an if statement to show timestamp in diffForHumans format for timestamps less than less than 5 days old and in toFormattedDatesString for anything older than that.

For example today is 31/10/17, so timestamp for 28/10/2017 should show - 3 days ago and timestamp for 20/10/2017 should show Oct 20, 2017.

Can someone please tell any logic to achieve this? Thanks in advance for the help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zjSiuC
via IFTTT

Laravel - Circle Ci use Vessel as container?

I am running laravel project and circle ci for continuous integration, now the problem I have now is me pulling a circle ci docker which does not contain necessary tools in order to get started:

version:                2

jobs:
  phpunit:
    working_directory:  ~/test

    docker:
      - image:          circleci/php:latest
      - image:          circleci/mysql:latest

I then have to download php extensions, chromium etc, I would like to use http://ift.tt/2yitH8b instead, Is it possible to integrate this vessel with cirle ci?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iM61Ds
via IFTTT

Laravel: Authentication Sentinel case sensitive username

I've been using this package http://ift.tt/1e4R6wc for user Authentication. I changed the login attributes to username instead of email.

I understand that if you are using email then case sensitiveness does not matter (http://ift.tt/2ihfajv), but with username it does. So when I have a username of root and I login with ROOT it still works as long as the password is correct.

Is there any way to change back the case sensitiveness?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2z20NYA
via IFTTT

how to find string in laravel blade template

How can I check data using something like strpos

data->url = http://www.youtube.come/12345

@if($data->url != 'youtube' )

@endif



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2hp5B2A
via IFTTT

Change localhost to custom server ip address in laravel

I 'ld like to use different server for my laravel project.For that i've changed my config/database.php code as,

        'host' => env('DB_HOST', 'http://192.168.1.15'),
        'port' => env('DB_PORT', '3306'),

And in .env file,

        APP_URL=http://192.168.1.15,

But it still access my localhost.How can I do this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zTsPoi
via IFTTT

vue js failed to "reactive"

i am following this tutorial http://ift.tt/2zSOXik. the page works fine without error on console but i cant change the message via console to showing "app2.message" and give me error "#app2 is not defined". its not working like they said

We have already created our very first Vue app! This looks pretty similar to rendering a string template, but Vue has done a lot of work under the hood. The data and the DOM are now linked, and everything is now reactive. How do we know? Open your browser’s JavaScript console (right now, on this page) and set app.message to a different value. You should see the rendered example above update accordingly.

enter image description here

here is my script:

window.addEventListener('load',
function() {

    var app2 = new Vue({
        el: '#app-2',
        data: {
            message: 'You loaded this page on ' + new Date().toLocaleString()
        }
    })

}, false);

this is how i include the js

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="">
<title>3R Inventory | @yield('title')</title>

<!-- Fonts -->
<link href="http://ift.tt/2dHeAcp" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="">
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
</head>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2hpfZY5
via IFTTT

Laravel OrderBy OneToMany Relation

I have 2 tables events_users: Which stores information about people that have attended certain events. Many people attend many events, hence using this linking table.

+--------+---------+---------+
|  eid   | user_id | slot_no |
+--------+---------+---------+
| event1 | user1   |       0 |
| event1 | user2   |       1 |
| event2 | user3   |       0 |
+--------+---------+---------+

And events_user_score: Which records the different scores of people at the events. At different events there can be lots of different score types, which is why this is in its own table, rather than as columns in the first table

+--------+---------+------------+--------+
|  eid   | user_id | score_type | number |
+--------+---------+------------+--------+
| event1 | user1   |          1 |      4 |
| event1 | user1   |          2 |      3 |
| event2 | user3   |          1 |      6 |
+--------+---------+------------+--------+

I'd like to be able to sort a selection of the first table, based on the figures in the second table. So would love to get a join working that would get a result like this. In effect turning score_type into columns, with the number as the value.

+--------+---------+---------+---+---+
|  eid   | user_id | slot_no | 1 | 2 |
+--------+---------+---------+---+---+
| event1 |   user1 |       0 | 4 | 3 |
| event1 |   user2 |       1 |   |   |
| event2 |   user3 |       0 | 6 |   |
+--------+---------+---------+---+---+

So far i've tried using laravel's "hasMany" but i can't sort using that technique. So am looking at trying a left join of some type, but have got really confused as now i'm not getting any score back:

$attendees = Events_user::whereIn("events_users.eid", $lastWeeksEvents->pluck('eid'))->where("slot_no",">=",0)
                            ->leftJoin('event_user_score', function ($join) {
                                $join->on('events_users.eid', '=', 'event_user_score.eid')
                                     ->where('events_users.uid', '=', 'event_user_score.uid');
                            })
                        ->get();

Assume that $lastWeeksEvents returns a list of events with the eid's matching those in the first table.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iLSprR
via IFTTT

lundi 30 octobre 2017

Laravel query from collection

I'm trying to filter Members who have Groups that are of a different type through the relations. I want it to filter it to only those Members, but instead it seems to still return all members of that type. This is the code I've been using:

$members = Member::where('type', 1)->with(['groups' => function ($query) {
      $query->where('type', 0);}])->get();

What I want is something like this (although this generates an error):

$members = Member::where('type', 1)->where(['groups' => function ($query) {
      $query->where('type', 0);}])->get();

Is there a different approach I could use do this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iNr08S
via IFTTT

The Auth password reset link sent by email is wrong

The link that I receive to the email to reset my password is not well formed:

should be:

http://localhost:8000/password/reset/sometoken

but instead I receive

http://localhost/password/reset/sometoken

the other routes of Auth work well, any idea? Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yZPFxG
via IFTTT

Laravel Project with Netbeans

I want to create a Laravel 5 project using Netbeans. Creating the project, on the last step, I have to choose "Composer". There I type in "Laravel" and select "laravel/laravel". Then, I get the message "Composer could not find a composer.json file in /home/username". However, manually, I can create a laravel project using Composer. Can you help me out what I can do, to create the project using Netbeans?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gOB79d
via IFTTT

Twilio Fax: Schema validation warning - 12200

My Controller Code for incoming fax:

$twimlResponse = new \SimpleXMLElement("<Response></Response>");
$recieveEl = $twimlResponse->addChild('Receive');
$recieveEl->addAttribute('action', '/api/fax/received/file');       
return response($twimlResponse->asXML(), 200)
      ->header('Content-Type', 'text/xml');

Output of my incoming web hook defined by above code

<?xml version="1.0"?>
<Response>
    <Receive action="/api/fax/received/file"/>
</Response>

Twilio Error Log (Warning message)

Msg: XML Validation warning
line: 2
parserMessage: Invalid content was found starting with element 'Receive'. One of '{Play
ErrorCode:12200
cols:79
LogLevel:WARN
url:http://......./api/fax/incoming

http://ift.tt/2ih5VQA

http://ift.tt/2gNpdwg



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ifT0OF
via IFTTT

LaraAdmin Uploads manager use the one to many relationship

I have installed and configured the LaraAdmin. I need the use of LaraAdmin Uploads manager tools, But I need the relationship like one to many of product and its images. So one product has many images. But in the LA upload manager not providing it. How can i do it with Upload manager.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2hnxDLN
via IFTTT

Force download of PDF in Laravel 5.5

On a page I have a link:

<a href="" target="_blank" title="download PDF">@fa('download')</a>&nbsp;&nbsp;

and in the web.php I have:

Route::get('downloadWirebird/{id}','FrontController@downloadWirebird')->name('downloadWirebird');

In FrontController I have:

public function downloadWirebird($id)
                {
                  $wbd = Wirebird::find($id);
                  $fileName = asset('Wirebird')."/".$wbd->PDF;
                  $headers = ['Content-Type: application/pdf'];
                  return response()->download($fileName, $headers);
                }

All the paths are correct but when I click on the link absolutely nothing happens.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zQFGYi
via IFTTT

Mixed Content (laravel)

I get the following error (on every page)

app.js:703 Mixed Content: The page at 'https://sitename.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://ift.tt/2gNm7Zf'. This content should also be served over HTTPS.

The site is build with Laravel. Is there anybody who knows how to fix this error?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2igqIn1
via IFTTT

Prevent showing error when multiple clicking on link tag

My question is: how to prevent application from throwing

Call to a member function destroy() on null

on user's browser when fast/double clicking on a link HTML element on a laravel project:

<a href="{!! route('models.destroy', $model->id) !!}" class="btn btn-danger>Confirm</a>

For a similar problem with form submit buttons I used kjdion84's answer:

$('form').submit(function (event) {
    if ($(this).hasClass('submitted')) {
        event.preventDefault();
    } else {
        $(this).find(':submit').html('<i class="fa fa-spinner fa-spin"></i>');
        $(this).addClass('submitted');
    }
});

But the adaptation I tried didn't work out, either with class or id selectors:

$('a .btn-danger').click(function (event) {
    if ($(this).hasClass('pressed')) {
        event.preventDefault();
    } else {
        $(this).addClass('pressed');
    }
});

I also tried this simpler answer, but event.preventDefault() doesn't seems to work and using dblclick doesn't make a difference.

I'm open to other than Javascript ways of solving this.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2z2eMiY
via IFTTT

Skip authorization while functional testing a Laravel application

Is there a built-in way to skip authorization completely while testing the controllers?

Sample controller:

public function changePassword(Request $request, LdapInterface $ldap)
{
    $this->authorize('change-password');

    $this->validate($request, [
        'pass' => 'min:8|confirmed|weakpass|required', 
    ]);

    $success = $ldap->updatePassword($request->get('pass'));

    $message = $success ?
        'Your e-mail password has been successfully changed' :
        'An error occured while trying to change your alumni e-mail password.';

    return response()->json(['message' => $message]);
}

I want to skip change-password rule, which is defined inside the AuthServiceProvider like:

public function boot(GateContract $gate)
{
    $gate->define('change-password', function ($user) {
        // Some complex logic here
    });
}

I don't want to add smt. like if (env('APP_ENV') == 'testing') return; inside the code.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gVB0N3
via IFTTT

Laravel 5.5 Cookie doesn't store

I want to store a custom cookie in user browser and in a register form. I would create an affiliate system.

I test the basic cmd with this:

http://ift.tt/2iJHMFZ

In my controller

    $ref = $request->query('ref');

    $cookie = Cookie('referral', $ref , 60);

    dd($cookie);

The dump of cookie created works perfect. cookie name, value, expire... But nothing is save into user browser. I have used firefox developpment web to check all cookies in browsers. see this image: cookie is missing in browser

Browser doesnt store cookie. Why?

Nb: I have used also this package http://ift.tt/2iLGIBI but its the same problem.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zjo6jB
via IFTTT

Create Filterable / Sortable HTML table Laravel PHP MySQL

I am using Laravel 5.5 and trying to find out if there is a streamlined way to filter / search through a database table in an html form / view.

I have had no trouble getting a table to show up, and also have been able to filter results easily enough by passing a variable into the url with:

onchange = "javascript:window.location"

That sort of thing seems to work pretty well with one drop down, but if I have 5 drop downs, and I want each one to change which records are displayed on the screen, and each one to not have to be supplied, I have been having issues.

Is there an easy way to do this? So far the best thing I have come up with is adding an apply button, and when you click the apply button, it uses the selected items from the dropdown menus to save a string into a variable, and then using the string variable to to reload the url with the string attached, and then unparse the string back into several variables in the controller.. but is that really necessary?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zjo4bt
via IFTTT

Laravel Advanced Having?

How do I use advanced having clause same as where clause in below code? Getting error Method having does not exist.

$follows=$request->get('follows');
        $db = DB::table('tabel_1 as tbl')
            ->leftJoin('table_2 as tb2', 'tbl.col1', '=', 'tb2.col1')
            ->leftJoin('table_3 as tb3', 'tbl.col1', '=', 'tb3.col1')
            ->select('tbl.col1','tbl.name','tb2.insta_followedByCount','tb3.twit_followers_count',DB::raw('SUM(tb2.insta_followedByCount+tb3.twit_followers_count) as ptotal'))
            ->groupBy('tbl.col1','tbl.name','tb2.insta_followedByCount','tb3.twit_followers_count')
            ->orderBy('ptotal', 'desc')
            //->having('ptotal', '>=', 5000000)
            ->get();

            if($follows){
            $db = $db->having(function ($query) use ($follows) {
            $query
            ->having('ptotal', '>=', $follows);             
            });          
            }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iJHBdN
via IFTTT

Laravel Eloquent distinct timestamp's year

On some indexes I have selectboxes that filter results, 1 of them filters by year. But this selectbox only needs the years present in the related table. After doing some research on the net I came up with this:

public function getAvailableYears(string $column)
{
    $years = $this->model->selectRaw("substr({$column},1,4) as year")
                         ->distinct('year')
                         ->pluck('year', 'year')
                         ->toArray();

    return ['' => 'All'] + $years;
}

This perfectly produces an array ready to be inserted into Form::select()

I was wondering if there is a better way to do this. It seems to work fine since the timestamps always start with the year, but I am not sure about performance or other issues I might encounter in the future. Any expert insight would be awesome.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iITosN
via IFTTT

How do I pass data from my controller to a view in Laravel 5.5?

I have a function that I'm trying to pass some data to a view. I can't get the Route to recognize the data, it just keeps saying my variables are undefined. Here's what I'm trying to do:

return redirect('confirm')->with([
   'name'=>$name,
   'service'=>$service,
   '$email_address'=>$email_address
]);

Then in my web.php file, I have:

Route::get ('confirm', function($name,$service,$email_address){

return view('confirm',compact('name','service','email_address'));
})->name('confirm');

Laravel just throws an error "Missing argument 1 for Illuminate\Routing\Router::{closure}()"

I'm at a complete loss, I've tried this a bunch of different ways. If I call the view right from my controller, it works fine, but then URL isn't what I want it to be, so it seems like I have to return the redirect and reference the data in my route definition. Can anyone enlighten me?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lrOD83
via IFTTT

Laravel: How to change `to` filed of reiceipt in mail?

I found in the docs how to change the name of the sender but not where to specify the to field. I also did not find anything in the config/mail.php file.

When I send something to user Max Mustermann like this:

$user = \App\User::where('name','=','Mustermann')
                   ->where('vorname','=','Max')->first();
\Mail::to($user)->send(new Mail());

the mail will be send to

Mustermann < test@email.net >

but I want to send it to

Max Mustermann < test@email.net >

Where can I change this setting?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2igMU0r
via IFTTT

Laravel/Vue - refreshing JWT token

I am using tymon jwt auth package in laravel for token authentication and I am trying to refresh a JWT token if it is expired, I have set up a middleware AuthenticateToken, that looks like this:

class AuthenticateToken
{
    public function handle($request, Closure $next)
    {
        try
        {
            if (! $user = JWTAuth::parseToken()->authenticate() )
            {
                return response()->json([
                    'code'   => 401,
                    'response' => null
                ]);
            }
        }
        catch (TokenExpiredException $e)
        {
            // If the token is expired, then it will be refreshed and added to the headers
            try
            {
                $refreshed = JWTAuth::refresh(JWTAuth::getToken());
                $user = JWTAuth::setToken($refreshed)->toUser();
                header('Authorization: Bearer ' . $refreshed);
            }
            catch (JWTException $e)
            {
                return response()->json([
                    'code'   => 403,
                    'response' => null
                ]);
            }
        }
        catch (JWTException $e)
        {
            return response()->json([
                'code'   => 401,
                'response' => null
            ]);
        }

        // Login the user instance for global usage
        Auth::login($user, false);

        return  $next($request);
    }
}

And I am using that middleware on my routes:

    Route::group(['prefix' => 'intranet', 'middleware' => ['token']], function () {
        Route::get('intranet-post', 'Api\IntranetController@index');
    });

And in Vue I have set up the axios and refreshing of the token like this:

// Apply refresh(ing) token
BACKEND.defaults.transformResponse.push((data, headers) => {
  if (headers.authorization && store('token', headers.authorization)) {
    BACKEND.defaults.headers.common.authorization = headers.authorization;
  }
  return data;
});

BACKEND.defaults.transformRequest.push((data, headers) => {
  headers.authorization = `Bearer ${load('token')}`;
});

Vue.prototype.$http = axios;
Vue.prototype.$backend = BACKEND;

function store(key, value) {
  try {
    let oldLength = localStorage.length;
    localStorage.setItem(key, value);
    return !(localStorage.length > oldLength); // Returns true on write error
  }
  catch (err) {
    return true;
  }
}

function load(key) {
  try {
    return localStorage.getItem(key);
  }
  catch (err) {
    return null;
  }
}

But, on expiration of the token I still get 403 response. How can I fix this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yXPTpb
via IFTTT

Eloquent tables in Laravel 5

I work by a company with college What i programming is a web to make my college register what he/she online has ordered. Let's begin with my tables:

Services table:

--------------------
  id  |    name    |
--------------------
  1   |    DHL     |
--------------------
  2   |    TNT     |

User table:

--------------------
  id  |    name    |
--------------------
  1   |   Safwan   |
--------------------
  2   |    Niels   |

Packeges table:

---------------------------------------------
  id  | package_name | user_id | Services_id |    
---------------------------------------------
  1   |     Mouse    |    1    |      2      |
---------------------------------------------
  2   |   Keyboard   |    2    |      1      |

user_id is foreign with User.id and Services_id is foreign with Services.id

View controller:

public function index()
{
    // get all packages
    $package = package::all();

    return view('Pages.view', ['package' => $package]);


}

view.blade.php:

<h1>The ordered packages</h1>

            @foreach($package as $packages)
                
            @endforeach

Now what i want is that: Safwan ordered Mouse via TNT



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xxFigv
via IFTTT

Laravel: Mail markup for single newline?

When I hit return in the email.blade.php file it does not create a new line. However, according to the markdown rules it should.

Thats my blade file:

@component('mail::message')
# Introduction

First line
Second line

third line...
@endcomponent

and that is how it looks in my browser:

enter image description here

Why is there no line break before Second line?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yVTLXJ
via IFTTT

Call to any public method of class work on develop area but not in production

I've a package for use with Laravel 5.5. This package work fine juts at yesterday on production and develop servers.

On my controller:

use Abkrim\Farid2Es\Farid2Es;
...

$es = New Farid2Es($request);
$params = $es->getParamsElasticSearch("searchProposals");  // Here fail on production server

On class file on vendor/abkrim/farid2es/src/Farid2Es:

namespace Abkrim\Farid2Es;

class Farid2Es {
function __construct($request)
{
    $this->request = $request;
}

/**
 * Method to perform the works depending on the type of action to be performed with ElasticSearch
 *
 * @param $action
 * @return array
 */
public function getParamsElasticSearch($action) {
    switch ($action) {
        /*
        case 'newProposal':
            $params = $this->setNewProposaltoEs();
            break;
        */
        case 'searchProposals':
            $params = $this->setParamsSearchProposals();
            break;
        case 'matchingProposals':
            $params = $this->setParamsWithScoringScript();
            break;
        default:
            // error
    }

    return $params;
}
}

When instance class not error. But line for call method fails I try put below for see list of all public methods, but get same error.

$es = New Farid2Es($request);
dd($es->getMethods(ReflectionMethod::IS_PUBLIC));

Develop server has PHP 7.1.X Production server has PHP 7.0.X



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2A0fIT6
via IFTTT

Convert raw MySQL into Laravel 5 query

select calendars.datefield AS date,
ifnull(sum(sales.sale_total),0) as total
from sales 
right join calendars on (date(sales.created_at) = calendars.datefield)
where (calendars.datefield between (select min(date(created_at)) from sales) and (select max(date(created_at)) from sales))
group by date

Want to convert it into Laravel 5 query. I am running Laravel 5.4. Any help?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xApx8r
via IFTTT

Laravel array validation in 5.5 version

Validation code

'event' => 'required|array',
'event.*.start_date_time' => 'required|date_format:Y-m-d|after:today',
'event.*.end_date_time' => 'required|date_format:Y-m-d|after:today',
'event.*.description' => 'required|spam_free',

Error message code

if ($messages->has('event')) {
    $fieldId = 'event';
    $errors [] = getErrorMessage($fieldId, $messages->first($fieldId));
}
if ($messages->has('event.*.start_date_time')) {
    $fieldId = 'event.*.start_date_time';
    $errors [] = getErrorMessage($fieldId, $messages->first($fieldId));
}
if ($messages->has('event.*.end_date_time')) {
    $fieldId = 'event.*.end_date_time';
    $errors [] = getErrorMessage($fieldId, $messages->first($fieldId));
}
if ($messages->has('event.*.description')) {
    $fieldId = 'event.*.description';
    $errors [] = getErrorMessage($fieldId, $messages->first($fieldId));
}

Error message

{
   "fieldld": "event.*.start_date_time",
   "message": "The event.0.start_date_time field is required."
},
{
    "fieldld": "event.*.end_date_time",
    "message": "The event.0.end_date_time field is required."
},
{
    "fieldld": "event.*.description",
    "message": "The event.0.description field is required."
},

Array

event[0].start_date_time:2017-03-22 15:42:22
event[0].end_date_time:2017-03-22 15:42:22
event[0].description:test description

Can anyone help my why its not validation array and why i am not getting proper error message.

Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gMcA4T
via IFTTT

Laravle Passport authentication issue on AWS server

I'm using Laravel 5.5 with passport's for api services. Its working fine after adding the "client credentials" route middleware in local.

'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class

Local Setup :

URL: http://localhost/server/public/index.php/api/v1/user/1

I got response as,

{
"status": 200,
"response_time": 0.050323009490967,
"body": {
    "user": "admin",
    "email": "admin@domain.com"
},
"message": "User found"

}

AWS Setup :

But, when i move to AWS server it won't authenticated.

URI: http://ift.tt/2hmT6V2

I got error as,

{
 "message": "Unauthenticated."
}

Both installations are same, and i can get access-token and reset-token by its endpoints.

But POST/GET/PUT/DELETE API calls are now allowed in AWS server.

Why it's not supporting on AWS ?

Any other ways to solve this ?

[Note: "web" group's "POST/GET/PUT/DELETE" routes are working fine.]



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ieku7j
via IFTTT

Laravel: Class 'App\DB' not found

I am trying to use DB class to run query. I have used it in my controller like this:

use \DB;

And I am using it in my code like this:

$changeCar = DB::select(DB::raw($query));

I have tried including it like this:

use Illuminate\Support\Facades\DB

But still the same. Also, tried it with the backslash in the code and not including it like this:

$changeCar = \DB::select(\DB::raw($query));

Still the same. What am I doing wrong here? Any help?

P.S: My laravel version is 5.4.33



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2idfPSY
via IFTTT

Laravel model binding for select dropdown

I want the select dropdown value to be selected in my edit form.In my controller,

public function edit($id)
{

        $vedit = DB::table('vehicles')->where('id', $id)->first();
        $cartype= DB::table('car_category')->pluck('cartype'); 
        return view('vehicles.edit', compact('vedit','cartype'));
            }

In view,


 <select name="vehicle_type" class="form-control">
@foreach($cartype as $cartypes) 
 <option value=""></option>
@endforeach
</select>

How can I achieve this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xztlqI
via IFTTT

Vuejs go to anchor after redirection

in my <div id="app">.....</div> i have something like the following

        <div class="fp-row4-content">
            ... ROW 1 ...
        </div>
            <div class="partition-line"></div>
        <div class="fp-row4-content">
            ... ROW 2 ...
        </div>
            <div class="partition-line"></div>
        <div class="fp-row4-content">
            ... ROW 3...
        </div>
            <div class="partition-line"></div>
        <div class="fp-row4-content">
            ... ROW 4 ...
        </div>
            <div class="partition-line"></div>
        <div class="fp-row4-content">
            ... ROW 5 ...
        </div>

If I click on each of these row, they will bring me to the same page. But after the page load, I want them to jump to 5 different specific anchor.

Is it possible to do it with Vuejs (I am using Laravel) ? Will vue-router do the job? Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2A0m1G0
via IFTTT

laravel-Auto increment Id

How to get auto increment Id?I created the database.It has customer registration form.Customer Id is auto-generated in DB.I want to fill Id input field by a max value of Id column.ex:example



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yVpmIP
via IFTTT

Laravel 5 get attribute from collection

I have a $location collection that looks like this:

Collection {#225 ▼
  #items: array:5 [▼
    0 => GoogleAddress {#336 ▼
      -id: "ChIJjWwHAP72w0cR44_HJ-bRcJE"
      -locationType: "ROOFTOP"
      -resultType: array:1 [▶]
      -formattedAddress: ""
      -streetAddress: null
      -intersection: null
      -political: ""
      -colloquialArea: null
      -ward: null
      -neighborhood: null
      -premise: null
      -subpremise: null
      -naturalFeature: null
      -airport: null
      -park: null
      -pointOfInterest: null
      -establishment: null
      -subLocalityLevels: AdminLevelCollection {#339 ▶}
      -coordinates: Coordinates {#331 ▶}
      -bounds: Bounds {#332 ▶}
      -streetNumber: "21"
      -streetName: ""
      -subLocality: null
      -locality: ""
      -postalCode: ""
      -adminLevels: AdminLevelCollection {#337 ▶}
      -country: Country {#335 ▶}
      -timezone: null
      -providedBy: "google_maps"
    }
    1 => GoogleAddress {#344 ▶}
    2 => GoogleAddress {#352 ▶}
    3 => GoogleAddress {#360 ▶}
    4 => GoogleAddress {#368 ▶}
  ]
}

So I am trying to get the formattedAddress like this:

$location[0]->formattedAddress

But I get the following error:

Cannot access private property Geocoder\Provider\GoogleMaps\Model\GoogleAddress::$formattedAddress

Anyone can help me out here?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2z3aDeM
via IFTTT

how to remove a empty header row in larvel excel

I am using laravel excel for importing my excel sheet data. The problem i am having is, i have a excel sheet with heading on the first row and there is a empty header row in it. I want to not consider that header as it is altering the design of my import. How do i do that? and also when there are special characters in the header its converting them to _ and throwing a error Undefined property: stdClass::$bank_name_. So how do i avoid empty rows and Colomns in laravel excel. i tried ignoreEmpty() but it wasnt working .

[$find = Excel::selectSheetsByIndex(0)->load($path, function($reader) { $reader ->ignoreEmpty()
      })->get();][1]

I attached a sample image of my excel and code. excel sheet image



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ziAlNl
via IFTTT

Laravel - Session key change in everypage refresh does not match to requested token - Failed to Verifytoken Error

I am stuck with a very strange problem. I am not able to login using middleware. I guess just because the session token does not match the request token. How can I fixed this?

When I request to login. request token does not match the session token. However Session token changes every page refresh but requested token remains same. Finally I checked what exactly session and request token going ahead. as mentioned below

array:2 [▼
  "SessionToken" => "YDThBgfxnV6Lqv3STD2QF4l9IL2OQC7l2dN5LDJv"
  "RequetedToken" => "vhEp8swYB7sXNxg6GEzfgjrSDTAP7SuFo8Z57Psf"
]

Some Questions in my mind like.

why the same project is running perfectly fine on my another server and localhost? if there any server session issue? Why my session key and requested token is different? I am not using any kind of angular vue in this project. Please help me if anyone have the idea regarding this issue? Thanks alot



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iNthBj
via IFTTT

connect remotely to online database online with local phpmyadmin(xampp)

now I deployed laravel project on digitalocean vps cloud (LEMP Stake , Ubuntu 16)
I want Access to my database remotlty from local phpmyadmin (xampp)
I try to modify config.inc.php by put domain / IP address to connect mysql online server but this don't work
my xampp version 3.2.2
any suggesting to do this ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yWzlv6
via IFTTT

dimanche 29 octobre 2017

Leaving reviews on multiple products and Laravel relations

I have order system and when user order some product he then can leave feedback for the product.

My issue is when there are multiple products in same order. I want to place button on each product leave feedback.

In my controller I have this

public function orderView($orderId)
{       
    $order = Order::where('order_id', $orderId)->where('status', 1)->where('user_id', Auth::user()->user_id)->first();
    $reviews = Review::where('user_id', Auth::user()->user_id)->get();        

    return View::make('order_details', [
        'order' => $order,
        'reviews' => $reviews
    ]);
}

The function query the orders table and reviews table. Then on the page I'm trying to do this

@foreach($reviews as $review)   
    @if($item->product_id == $review->product_id)                                   
        @if($review->rating_published == 0)
            <a class="btn btn-warning" href="">Wating for Approval</a>
        @else   
            <a class="btn btn-warning" href="">Edit Review</a>                                  
        @endif                                          
    @else
        <a class="btn btn-warning" href="">Leave Review</a>
    @endif
@endforeach

For now the problem is that if there is no reviews from logged user I don't see "leave review" button on page.

My review model have

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

Product model

public function reviews()
{
    return $this->hasMany('App\Review', 'product_id'); 
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xyT0Q4
via IFTTT

Join two table and read second table multiple data with first table in laravel

I wanna join two table in laravel , reads one record from first table and multiple record from second table. The first table has some field that I want to select all. The second table has been connected to first table with foreign key. Show multiple records using comma.

First Table:
-----------
+----+-------------+
| id | some_fields |
+----+-------------+
| 23 |    S.V      |
+----+-------------+
| 24 |    S.T      |
+----+-------------+
| 25 |    S.M      |
+----+-------------+

Second Table:
------------
+----+----------+------------+
| fid| meta_key | meta_value |
+----+----------+------------+
| 24 |   meta_1 |   m_1      |
+----+----------+------------+
| 24 |   meta_2 |   m_2      |
+----+----------+------------+
| 25 |   meta_2 |   m_3      |
+----+----------+------------+

 Output that I want:
+----+-------------+----------------+
| id | some_fields |  meta_value    |
+----+-------------+----------------+
| 24 |     S.T     |   m_1  ,  m_2  |
+----+-------------+----------------+
| 25 |     S.M     |      m_3       |
+----+-------------+----------------+



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ifhUhy
via IFTTT

Problems with fetching Firebase data in Karma-jasmine and Vue.js

Here I have a laravel project and currently using Karma and jasmine for JS testing.

But Firebase is not executed properly, because the test file cannot receive any data fetched from firebase; seems failed to executed db.ref().on() actions.

By checking the console log, the data in vue.js is always empty. But the real application works fine.

So I'm guessing it should be wrong with my spec.js or config.js and I added a few print statements to check my Vue file (short version):

<template>
<div>
    <div v-for="item in log">
        <div></div>
    </div>
</div>
</template>


<script>
    import firebase from 'firebase';
    import moment from 'moment';

    var config = ......................;
    firebase.initializeApp(config);

    const db = firebase.database();

    export default{
        data(){
            return {
                log: []
            }
        },

        props: ['id','teamId'],

        mounted() {
            console.log('start to load...');
            const vm = this;
            db.ref('/teams/' + teamId + '/messages/').on('value', function(snapshot) {
                console.log('loading...');
                vm.log = snapshot.val();
            });
            console.log('finish...');
    }
</script>

The loading... statement never printed out. And actually same situation as saving data into firebase (not shown here). Therefore vm.$el is showing empty state

Here is the Console result:

LOG: 'start to load...'
LOG: 'finish...'
LOG: '<div><div><div></div></div></div>'
LOG:Object{log:[]}

.....
Expected '' to contain 'something'.
    at __WEBPACK_IMPORTED_MODULE_0_vue__.a.nextTick (tests/Vuetests/SendMessage.spec.js:9:1769408)
    at Array.<anonymous> (tests/Vuetests/SendMessage.spec.js:9:1798753)
    at nextTickHandler (tests/Vuetests/SendMessage.spec.js:9:1796193)
    at <anonymous>
Chrome 61.0.3163 (Mac OS X 10.11.6): Executed 1 of 1 (1 FAILED) ERROR (0.807 secs / 0.129 secs)

And here is my karma testing file:

import Vue from 'vue';
import Chat from "../../resources/assets/components/message/Chat.vue";

describe('UI Test', () => {

    let vm;

    it('should test input form.', () => {
        const Constructor = Vue.extend(Chat);
        vm = new Constructor({ 
             propsData:{
                 receiverUuid: "123",
                 teamId: "456"
             }
         }).$mount();
         console.log(vm.$el);
         console.log(vm.$data);
         expect(vm.$el.textContent).toContain("something")
    });
});

here is my karma.config.js

module.exports = function(config) {
  config.set({

    basePath: '',
    frameworks: ['jasmine'],

    files: [
    'resources/assets/components/message/Chat.vue',
      'tests/Vuetests/*.spec.js'
    ],

    exclude: [],

    preprocessors: {
      'resources/assets/components/message/Chat.vue': ['webpack'],
      'tests/Vuetests/*.spec.js': ['webpack','coverage']
    },

    reporters: ['progress', 'coverage'],

    coverageReporter: {
      type: 'html',
      dir: 'coverage/'
    },
    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    autoWatch: true,

    browsers: ['Chrome'],

    singleRun: false,

    concurrency: Infinity,

    webpack: {
      module: {
        loaders: [
          {
            test: /\.js$/,
            loader: 'babel-loader',
            include: ['resources','test'],
            exclude: /node_modules/,
            query: {
              presets: ['es2015'],
              plugins: ['istanbul']
            }
          },
          {
            test: /\.vue$/,
            loader: 'vue-loader'
          }
        ]
      }
    }

  })
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2z1AjIu
via IFTTT

how to include (file.form) blade.php file with another blade file in laravel

in my laravel project management application I have project and one project can create many tasks and one task have publish many files regarding to the task. so, in my file attachment form is this in files folder in view file

files/form.blade.php

@foreach ($task->project->files as $file)
                <div>
                    <div><i class="fa fa-check-square-o"></i>
                        <span>

                            <a href="" target="_blank"></a>
</span>
                    </div>
                </div>
                <hr/>
                @endforeach

        <form class="form-vertical" role="form"
                                    enctype="multipart/form-data"
                                    method="post"
                                    action="">
            <div class="form-group">
                <input type="file" name="file_name" class="form-control" id="file_name">
                @if ($errors->has('file_name'))
                    <span class="help-block"></span>
                @endif
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-info">Add Files</button>
            </div>
            <input type="hidden" name="_token" value="">
        </form>

and file model relationship with Task model is this

public function task(){
    return $this->belongsTo(Task::class);
}

Task model relationship with File model is this

public function files(){
    return $this->hasMany('App\File');
}

and now I included files/form.blade.php file with tasks/show.blade.php file as this

tasks/show.blade.php

<h2></h2>
<hr>


<hr>

{!!$task->body!!}

<hr>
@include('files.form')

then when I try to view task/show.blade.php file this following error is coming

Undefined variable: task (View: C:\Users\Lilan\Desktop\ddd\resources\views\files\form.blade.php)

how can fix this problem?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iehQ1w
via IFTTT

Using Laravel Service Container For Third Party APIs

I'm trying to make good use of Laravel's Service Container to instantiate a connection to a third party API and use it properly across my Controllers. Below is a Service I created and a basic Controller but it doesn't seem to be working the way I'd expect. Where am I going wrong? Should this be structured differently? How so?

namespace App\Services;

use App\Http\Clients\RestClient;

class RestApiService {

    private $api;

    /**
     * Return the API connection.
     *
     * @return array
     */
    public function connect() {

        $api = new RestClient();
        $api->setUrl(getenv('API_REST_URL'))
                    ->setUsername(getenv('API_USERNAME'))
                    ->setPassword(getenv('API_PASSWORD'))
                    ->connect();

        return $api;
    }
}

class UserController extends Controller {

    protected $api;

    public function __construct(RestApiService $api) {
        $this->api = $api;
    }

   public function index() {
        $users = $this->api->getUser(session('user_id'));

        return view('user.index', ['users' => $users]);
    }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gMJF0r
via IFTTT

Best Location In Laravel For Third-Party API Connection

I'm writing a Laravel application using one or more third-party APIs when it suddenly dawned on me. Where is the best place within the Laravel application structure to setup the API connection in order to consume it from within my Controllers? Would you use a Service or put the logic somewhere else?

$this->api = new RestApi();
    ->setUrl(getenv('API_REST_URL'))
    ->setUsername(getenv('API_USERNAME'))
    ->setPassword(getenv('API_PASSWORD'))
    ->connect();



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gUN29l
via IFTTT

Asynchronous Laravel Jobs

I want to run asynchronous Laravel jobs and work forever. As far as I understand, I need to setup Jobs and push them into separate queues.

I have set .env - QUEUE_DRIVER=database and run php artisan queue:table and php artisan migrate accordingly.

and I have run php artisan make:job MyJob

(at this point queues table is empty though, but I don't know if I did something wrong)

The point I mainly got confused is how is it going to start all the jobs and run them forever, or run the job initially?

As far as I understand, to trigger the job I need to call:

MyFirstJob::dispatch();

but where do I need to call it to work all the time and forever?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yduTeq
via IFTTT

TCPDF save file then redirect

I'm using laravel 5.4 and elibyy/tcpdf-laravel to generated view to PDF. Now I'm trying to save the file then redirect to another page.

I've tried like this, but it became just save and download the file. Not redirect me to the page I wanted.

$view = View::make('view', compact('anything'));
$html = $view->render();

$pdf = new TCPDF();
$pdf::setFooterCallback(function($pdfs) {
    $pdfs->SetY(-15);
    $pdfs->SetFont('helvetica', 'I', 8);
    $pdfs->Cell(0, 10, 'Page '.$pdfs->getAliasNumPage().' of '.$pdfs->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
});
$pdf::SetTitle('Title');
$pdf::AddPage();
$pdf::writeHTML($html, true, false, true, false, '');
$pdf::Output(public_path('path/to/location/file.pdf'), 'FD');

return redirect()->route('somewhere')->with('success', 'Success');



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zSroX3
via IFTTT

Laravel - refactor table names (migration) will Models/Controllers go with it?

I would like to rename a table in the database from topics to galleries and I have created a migration that will rename my table. Schema::rename('foo', 'bar');

<?php

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

class RenameTopicsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::rename('topics', 'galleries');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::rename('galleries', 'topics');
    }
}

However will the Topic Model and Topic Controller be automatically renamed? Or will I have to refactor my code? Does Laravel provide a way to do this easily?

In short my question is - How do you change your schema easily in laravel? (models/controllers/database/requests/transformers ect..)

Thanks!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ydsAIf
via IFTTT

Different headers in different views (Blade template, Laravel)

I use the Bladetemplate of Laravel. Is there a way to set different header for different views with only one include in master.blade.php?

master.blade.php

@include("elements.header")
  @yield('content')
  @section("footer")
  @show

view.blade.php

@extends("layouts.master")
    @section("title")

    @stop
    @section("content")
  @include("elements.error")

  @section("footer")
  @include("elements.footer")
  @stop



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gTXa1W
via IFTTT

Laravel/Eloquent conditions on subproperties don't apply

I have the following models:

  • Client
    • belongsToMany(Group)
  • Group
    • belongsToMany(Client)

What I wanted is an array of all groups, where each group contains the clients belonging to it.

I was able to achieve this with the following code:

Group::with('clients')->get();

Now I want to only get the groups and clients where the client's status property is 1. So if there are multiple clients in a group, then the result should not contain clients with a status !=1. Additionally, if this condition returns 0 clients for a group, the group should also NOT be contained in the final result.

What I tried so far:

Group::with(['clients' => function($query) {
  $query->where('clients.status', '!=', 1);
}])->whereHas('clients', function($query) {
  $query->where('clients.status', '!=', 1);
})->get();

Somehow, none of both where-conditions apply when I execute the query. What am I missing or doing wrong?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gT887R
via IFTTT

Copy one row from one table to another

I need a little help and I can’t find an answer. I would like to replicate a row from one data table to another. My code is:

public function getClone($id) {
 $item = Post::find($id);
 $clone = $item->replicate();
 unset($clone['name'],$clone['price']);
 $data = json_decode($clone, true);
 Order::create($data);

 $orders = Order::orderBy('price', 'asc')->paginate(5);
 return redirect ('/orders')->with('success', 'Success');
}

and i got an error :

"Missing argument 1 for App\Http\Controllers\OrdersController::getClone()"

. I have two models: Post and Order. After trying to walk around and write something like this:

public function getClone(Post $id) {
...
}

I got another error

Method replicate does not exist.

Where‘s my mistake? What wrong have i done? Maybe i should use another function? Do i need any additional file or code snippet used for json_decode ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2idqXPU
via IFTTT

Laravel: Eloquent query ignores provided data to insert?

I have a user model and I want to create a new row in the database like this:

Route::get('test',function(){

  $alias = \App\Helper\Alias::create(session('firstname') . ' ' . session('surname'));

  $user =  App\User::create([
      'username' => '123213123',
      'gender' => session('gender'),
      'title' => session('title'),
      'name' => session('firstname'),
      'vorname' => session('surname'),
      'geb' => session('brithday'),
      'email' => session('email'),
      'hideEmail' => session('emailVis'),
      'website' => session('website'),
      'tel' => session('tel'),
      'idSprache' => session('langC'),
      'bemerkungAnmeldung' => session('bem'),
      'alias' => $alias,
      'modeIN' => session('mode'),
  ]);
});

Now as soon as I go to /test/ in the browser I get the following error:

SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into profileMember (name, email, updated_at, created_at) values (Adam, test@mail.com, 2017-10-29 14:57:11, 2017-10-29 14:57:11)) enter image description here

The error is right: There is no default value for username and in the shown query there is no value given for username. However, in the above code I clearly provided the value 123213123 for the field username. Why is it ignored?


Some additional Screen shots:

Last application frame: enter image description here

Migration file:

enter image description here



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zVRhpH
via IFTTT

Login for multiple roles and permission

Hey I am making a project in which their are multiple users with different who are going to login. The users according to their role will be shown different pages. I have made a piece of code but whenever a user logins he/she can access the page of another user.

This is my login controller

 <?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 use App\User;
 use Auth;

 class LoginController extends Controller
{
public function login(Request $request)
{


    if(Auth::attempt([

        'email' => $request->email,
        'password' => $request->password

    ]))
    {
        $user = User::where('email', $request->email)->first();

        if($user->is_admin())
        {
            return redirect()->route('dashboard');
        }

        return redirect()->route('home'); 
    }
    redirect()->back();
}

}

These are my routes

  <?php


  Auth::routes();

  Route::get('/home', 'HomeController@index')->name('home');
   Route::post('/login/custom',[
 'uses' => 'LoginController@login',
 'as' => 'login.custom'
  ]);
  Route::get('/login/custom',[
 'uses' => 'LoginController@login',
 'as' => 'login.custom'
 ]);
  Route::group(['middleware' => 'auth'], function(){

Route::get('/home',function(){

    return view('home');
})->name('home');

  Route::get('/dashboard',function(){

  return view('dashboard');
 })->name('dashboard');

});

And this is my model

 <?php

 namespace App;

 use Illuminate\Notifications\Notifiable;
 use Illuminate\Foundation\Auth\User as Authenticatable;

  class User extends Authenticatable
  {
   use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

public function is_admin(){

    if($this->admin)
    {
        return true;
    }
    return false;
}

}

Please tell me what I am doing wrong.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2idVGwo
via IFTTT

Laravel Proper Relationship

So i have a 3 tables. Users-Inventory-Item. User hasmany Items, so far i have no problem. I can reach Items of User with this relationship.

Item table contains : user_id, item_id

So my problem is to reach item info of the Inventory of the User by item_id(which will find id of Item table and bring the info). I couldn't manage it, I need you advices about which relations would be the proper for my aim.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xxKHUY
via IFTTT

Laravel 5 Three-way One-to-Many Eloquent Relationship

I have database like this
opportunities

  • Id
  • contact_id

contacts

  • Id
  • User_id

users

  • id

User model :

class User extends Authenticatable
{

public function Contact()
{
    return $this->hasMany('Customer\model\Contact');
} 
}

Contact model:

 class Contact extends Model
{
    public function Opportunity()
   {
    return $this->hasMany('Sale\Model\Opportunity');
   }
  public function User()
{
    return $this->belongsTo('App\User');
} 
}

Opportunity model

class Opportunity extends Model
 {
       public function Contact()
    {
      return $this->belongsTo('Customer\Model\Contact');
    }
  public function User()
  {
   return $this->hasManyThrough('App\User','Customer\Model\Contact');
  }  
}

When on controller

  $Opportunity = Opportunity::with('User')->paginate(10);
  print_r($Opportunity->User);  

Show me wrong data.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xxJtJc
via IFTTT

Laravel Saved Text without Style and Spaces

how can i change in Laravel 5 the Text Style?

Example my Product description:

Its an Sample Product

You can buy it

#########for more info click here#########


You are welcome

I save it as the example and Laravel display it without line break:

Its an Sample Product You can buy it #########for more info click here######### You are welcome

I think i can change it in Controller?

Thanks for your Help



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iHQepj
via IFTTT

Remove query scope from auto-loaded resource in Laravel resource controller

In Laravel 5, if using a resource controller, the model gets loaded automatically and comes through in to the method.
However, I have a query scope checking if my model is active of not. For this one specific case, I'd like to remove that query scope, but leave it on the other methods in the class.

How can I do that? I assume it is in some middleware somewhere, but I can't find where.

Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yemcjR
via IFTTT

how to fix Undefined variable: task (View: C:\Users\Lilan\Desktop\ddd\resources\views\files\form.blade.php) in laravel

in my laravel project management application I have project and one project can create many tasks and one task have publish many files regarding to the task. so, in my file attachment form is this in files folder in view file

files/form.blade.php

@foreach ($task->project->files as $file)
                <div>
                    <div><i class="fa fa-check-square-o"></i>
                        <span>

                            <a href="" target="_blank"></a>
</span>
                    </div>
                </div>
                <hr/>
                @endforeach

        <form class="form-vertical" role="form"
                                    enctype="multipart/form-data"
                                    method="post"
                                    action="">
            <div class="form-group">
                <input type="file" name="file_name" class="form-control" id="file_name">
                @if ($errors->has('file_name'))
                    <span class="help-block"></span>
                @endif
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-info">Add Files</button>
            </div>
            <input type="hidden" name="_token" value="">
        </form>

and file model relationship with Task model is this

public function task(){
    return $this->belongsTo(Task::class);
}

Task model relationship with File model is this

public function files(){
    return $this->hasMany('App\File');
}

and now I included files/form.blade.php file with tasks/show.blade.php file as this

tasks/show.blade.php

<h2></h2>
<hr>


<hr>

{!!$task->body!!}

<hr>
@include('files.form')

then when I try to view task/show.blade.php file this following error is coming

Undefined variable: task (View: C:\Users\Lilan\Desktop\ddd\resources\views\files\form.blade.php)

how can fix this problem?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yZmiuV
via IFTTT

Encrypt ID in routers URL?

I have controllers like

Records, Items .... where I used ID /records/1, /records/2 .... /items/1, /items/2 .... Prompt the best variant at which it is possible to receive the cipher type of type / records / H $ Ur95% 92 (any hash) for all controllers (Records, Items ...). The first option was to create a table with the set id <-> hash and check the transmitted hash in the router. But I think this option is not quite right, because when adding a new record (ID), you need to record (check) the new hash. I think there is a simple option to do all this nicely through routers, without any additional tables. Like this

$id= Crypt::encrypt(['id' => 1 ]);
<a href="" target="_blank">get record</a>

And then check in router like

Route::get('/{id}', function($id){
 ..... Crypt::decrypt($id);............
});

Maybe find any other ways where we have global rules for all controllers to encrypt and decrypt IDs only in router area (without any guid/uuid).



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2loF89D
via IFTTT

Laravel Status Panel

Well how can I make Status Table For Student pair where he has to choose teacher and click on Add To Interest button which goes in to show status pending until accepted by admin and then it shows Accepted



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yUCxKi
via IFTTT

Form submission in laravel is not working and show token-mismatch Exception

i'm new laravel learner. i have create a form in laravel 5.4 and add two field one is textfield and another is submit button. i have create a name route for form submission. but when i submit the form it's show token mismatch exception. i can't find out error from my code. Here, is my form code.

<form method="post" action="">
    

    <input class="form-control" type="text" name="fname">
    <input type="submit" name="submit" value="Create">
</form>

here is my route,

Route::post('formsubmit','HomeController@formSubmit')->name('f.submit');

and here my controller,

 public function formSubmit()
{
    echo "Form Submitted";
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gTaNhQ
via IFTTT

Some errors in 'vendor/composer/autoload_static.php'

enter image description here

enter image description here

It happened suddenly, I never revise this file. 'vendor/composer/autoload_static.php'

But it looks like it can run properly.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zQSsG9
via IFTTT

samedi 28 octobre 2017

Get result was different in memcache && memcached?

The result for both memcahce and memcached different. Actually i'm using laravel 5.3 which is using memcached. i'm not getting result properly.

$em = new Memcached();
    $em->addServer('127.0.0.1', 11211);
    $em->get('test_key_1');
    Result => false

    $m = new Memcache();
    $m->addServer('127.0.0.1', 11211);
    $m->get('test_key_1');
    Result =>[
      [ 'user' => 12], [ 'user' => 13], 
    ]



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2z0kYIe
via IFTTT

constructor injection vs method injection

Laravel encourages dependency injection. Since I am using laravel on my project, I figured I'll try using this approach.

I am taking advantage of Laravel's service container by type hinting my dependencies and letting it resolve them. I have four controllers. All of them extend a base class called GlobalController. I also have two models. All of them extend a base class called GlobalModel.

My first attempt is (sort of) using method injection. GlobalController looks like this:

namespace App\Http\Controllers;

use Illuminate\Http\Request;;
use App\Models\GlobalModel;

class GlobalController extends Controller
{

    public function __construct()
    {
        $this->middleware(['authenticate', 'token']);
    }

    // functions that handle normal http requests and ajax requests

    }

One of the controllers that extends from GlobalController is called UserController. Some of its functions are:

  • index - show all data
  • edit - show edit form
  • update - updates to database

Edit and update use route-model-binding.

namespace App\Http\Controllers;

use Illuminate\Http\Request;;
use App\Models\User;

class UserController extends GlobalController
{

    public function index(User $user)
    {
        $users = $user->all();
        return view('pages/view_users')->with('users', $users);
    }

    public function edit(User $user)
    {
        return view('pages/edit_user')->with('user', $user);
    }

    public function update(Request $request, User $user)
    {
        $data = $request->all();
        if ($user->validate($data))
        {
            $user->update($data);
            return $this->successResponse($request, 'users', 'Successfully edited user');
        }
        return $this->failedResponse($request, $user);
    }

    // other functions

    }

While this is working fine, Request and User get injected many times. If I have to change a Request implementation (for example), I'll have to manually change many functions to type hint that particular Request object. Not good at all. Since they are usually called in most functions, I tried doing constructor injection.

Here is GlobalController using constructor injection:

namespace App\Http\Controllers;

use Illuminate\Http\Request;;;
use App\Models\GlobalModel;

class GlobalController extends Controller
{
    protected $request;
    protected $model; // use polymorphism

    public function __construct(Request $request, GlobalModel $model)
    {
        $this->request = $request;
        $this->model = $model;
        $this->middleware(['authenticate', 'token']);
    }

    // functions that handle normal http requests and ajax requests

}

And here is UserController using constructor injection containing the same functions:

namespace App\Http\Controllers;

use Illuminate\Http\Request;;
use App\Models\User;

class UserController extends GlobalController
{

    public function __construct(Request $request, User $user) // use polymorphism
    {
        parent::__construct($request, $user);
    }

    public function index()
    {
        $users = $this->model->all();
        return view('pages/view_users')->with('users', $users);
    }

    public function edit(int $id)
    {
        $this->model = $this->model->find($id);
        return view('pages/edit_user')->with('user', $this->model);
    }

    public function update(int $id)
    {
        $this->model = $this->model->find($id);
        $data = $this->request->all();
        if ($this->model->validate($data))
        {
            $this->model->update($data);
            return $this->successResponse('users', 'Successfully edited user');
        }
        return $this->failedResponse();
    }

    // other functions

}

Now, I can't put my finger on it, but I think this implementation seems not right. It became less readable. The usage of $model and $this have made the code more disgusting.

I am so confused. I understand the benefits I can get from dependency injection, but I am sure my implementations of method injection and constructor injection are extremely wrong. What implementation should I choose? Or should I choose any from these two at all?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zeVyrf
via IFTTT

Getting information from an array inside a foreach - PHP/Laravel

I'm developing an application with PHP using Laravel, and I have a problem.

I have a table with the name Account, in which it has a Code, CNPJ, ClientName columns (among others).

I've created an array of CNPJ's of clients (CNPJ is a unique identification of 14 characters for each client). I am giving a select in the table in which the information of these clients is located, and according to the cnpj of the array, I want to take the information of that client from my table to use them in my insert.

Currently my insert is working, but the variable $client->code is being inserted the value of 1 for all clients (each client has a unique code) and the $client->ClientName is returning null. I'm doing something wrong, but I do not know what it is.

Here is the output for the $client object:

stdClass Object ( [Number] => 1.0.0.00.00 [Status] => ACTIVE[ShortNumber] => 17 [Code] => 1 [Cnpj] => [ClientName] => )

OBS: this output information is from the first record in my table. For some reason, my array is being ignored.

OBS2: the variable $data-> Nfse->InfNfse->Service->Service->CpfCnpj->Cnpj is from an outside source, contains the CNPJ of a client (the unique identification of 14 characters for each client).

Heres the code:

$selectClients = DB::connection('sqlsrv2')->select('SELECT * FROM ConsultaCnpj.dbo.Account');

    $cnpjClients = array("43185230000185", "43037969000140", "52391703000191", "00697722000147", "35259696000150", "14189856000161", "11684590000135",
    "00299388000173", "12515276000191", "73800260000115", "26562892000108", "04711149000130", "11888864000108", "24193260000199", "34482091000160", 
    "10638562000119", "15615776000193", "22165071000187", "02505297000172", "03662446000170", "07863214000130", "34639419000100", "26619841000175", 
    "13738204000176", "62021837000174", "24417008000116", "11005444000136", "08303182000181", "84318799000159", "04768671000158", "00593411000138", 
    "06572788000197", "03875295000138", "08332733000135", "00237222000122", "06272868000127", "08336841000186", "04734406000159", "07647181000191", 
    "04769874000169", "08506339000176", "27149095000166", "34476101000155", "84042423000164", "13161344000124", "26753715000109", "23498256000176", 
    "00577473000156", "11425519000138", "90601147000120", "08077490000136", "04185220000198", "01646861000104", "02116365000101", "05379164000195", 
    "56319882000107", "15678394000109", "00581009000133", "08641589000119", "34918342000107", "11674272000193", "07801011000110", "30892350000170", 
    "87070843000142", "10456659000100", "44407989000128", "10338929000189", "06186786000160", "11674751000100", "08299638000187", "06274668000103", 
    "11578277000112", "73603748000152", "73392409000174", "05644027000130", "56321573000171", "60993482000150", "00085803000196", "87096616000196", 
    "57352635000175", "33658204000173");

    foreach ($selectClients as $client) {

            if (in_array($data->Nfse->InfNfse->TomadorServico->IdentificacaoTomador->CpfCnpj->Cnpj, $cnpjClients)) {

                //insert conta de debito (cliente)
                DB::insert('insert into LancaContaContabil (Codigo, DataOper, DespRateio, Valor, Receita, AgenteCobrador, 
                DespHistorico, Complemento, Orcado, Encerrado, CodigoContaContabil, LoteLanca,
                Rascunho, DC) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', 
                array($ult+1, $data->Nfse->InfNfse->Competencia, NULL, $data->Nfse->InfNfse->Servico->Valores->ValorServicos,
                0, NULL, 9182, $numero_nota . ', ' . $client->ClientName, 0, 0, $client->Code, $lanca, 0, 'D'));
            }
        }

Thanks guys.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zXn3CE
via IFTTT