lundi 31 juillet 2017

mix.options is not a function

I've been trying to run PurifyCSS for my Laravel app, but keep getting the "mix.options is not a function" error whenever I run 'gulp' from the command line. mix.styles works just fine though

I understand that this problem happened for a lot of people because they were on old versions of Laravel mix, however I believe I've updated it (eg npm laravel-mix -v returns "3.10.10")

Any advice? Thanks

var elixir = require('laravel-elixir');

elixir(function(mix) {
mix.options({ purifyCss: true });
mix.styles([
    'bootstrap.css',
    'cc.css'
]);
});



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

DB update query in Laravel?

i'm trying to update the 'hours_worked' column in "daiy_attendance" table using 'in_time' and 'out_time' in same table. in_time and out_time already stored in the table.so im using timediff to get the difference.query runs and execute correctly when i try it on the phpmyadmin sql format.but when i try to run it in the programme it does not update the 'hours_worked' column.it does not gives any errors also.

$sql5 = "UPDATE daily_attendances SET hours_worked = TIMEDIFF(out_time,in_time) WHERE in_time != '' AND out_time != '' ";
$result2 = DB::statement(DB::raw($sql5));



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

Trying to get property of non-object in my controller

I used two tables to retrieve data and view it on my product page. It worked properly but when I click the "add to cart" button it says 'Trying to get property of non-object'

This is my code:

public function getIndex()
 {
     //display all products
     $products = DB::table('products')
         ->join('categories', 'products.category_id', '=' ,'categories.id')
         ->select('products.*', 'categories.*')
         ->paginate(6);
     //display all mobiles category
     $mobiles = DB::table('products')
         ->join('categories', 'products.category_id', '=' ,'categories.id')
         ->select('products.*', 'categories.*')
         ->where('category_id', 1)
         ->paginate(6);
     return view('shop.index', ['products' => $products, 'mobiles' => $mobiles]);

 }
//add to cart controller 
 public function getAddToCart(Request $request, $id){
    $product = Product::find($id);
    $oldCart = Session::has('cart') ? Session::get('cart') : null;
    $cart = new Cart($oldCart);
    $cart->add($product, $product->id);

    $request->session()->put('cart', $cart);
    return redirect()->route('product.index');
 }



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

Two ajax posts the first one works fine while second one displays parserror

I'm really stuck here , please somebody help: I have two ajax calls with basically identical lines but only one works .

First Ajax post :

$("#languageswitcher").change(function(){


   var locale=$(this).val();
   //alert(111);
   //console.log(111);
  var _token =$("input[name=_token]").val();


   $.ajax({

      url:"/language",
       type:"POST",
       data:{locale:locale,_token:_token},
       dataType:'json',
       success:function(data){

         console.log(data);  
       },
       error: function(ts) {


           //alert(ts.responseText);
       },
       beforeSend:function(){
           console.log(locale);

       },
       complete:function(data){

           window.location.reload(true);

       }
      });

    }) ;

Second one: when i take off dataType:"json" it displays success on alert but send nothing , with the dataType:"json" it displays parserror on alert . i tried with JSON.stringfy() but still displaying the same problem .

$("#change_group").change(function(){

    var group=$(this).val();

    var _token=$("input[name=_token]").val();

    $.ajax({

       url:"/setgroup",
       type:"POST",
        data:{group:group,_token:_token},
        dataType:'json',
       success:function(data,status){
          alert(status);  
        },
       error:function(data,status){
            alert(status);
        },

       beforeSend:function(group){

        },
       complete:function(data){
            window.location.reload();
        }


       });



    });

What can be the issue here? Please somebody help , i'm stuck here for two days now .



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

Laravel array in lang

Is it possible to get an array element from Laravel lang files?

For example if i have a following array under resources/lang/en/my.php:

<?php

return [
  'fruit' => [1 => 'apple', 2 => 'orange', 3 => 'whatever'],
];

and now under my blade view i want to display a fruit a user has chosen:

@lang('my.fruits')[2]

... but this doesn't work.

How to get the second element of that array in my view?



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

Best laravel logging practice

I develop a pretty big web application using laravel. Logging to a single file or daily files seems too messy for me.

My purpose is to create error logs which will be categorised and easy for retrieval to show on front-end to tech support. E.g. user entered wrong api-key, email, whatever.

P.S. Users don't always understand meaning of the error showed so they contact tech support.

Example for better understanding:

So if I have model relations: User->hasMany->Project and in some project appears an exception I want it to be written and related to the project. e.t.c. So I could do something like $some_project_model->logs()->get() and tech support got all logs related to certain project.

What I have in my mind is separate table for logs which is related to certain Eloquent models. But to do so ExceptionHandler (which getting all the Exceptions) needs to know to which model an Exception is related to.

So how this can be implemented? Maybe I could assign certain ExceptionHandler to certain class?

I've found Eloquent logging guide and how to manually logging to separate files, but I need better.

Thank you for any suggestions.



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

How to implement MVC structure for large scale projects in laravel

I'm building a large scale project with laravel and I'm afraid about the mess structure .

maybe this question is not just relative to laravel but I asked someone for help and he suggested me using jobs for distributing the codes . he suggested calling jobs in every function of controllers and separate jobs and not writing any extra code in controllers! something like this

<?php

namespace App\Http\Controllers;

use App\Jobs\Page\ShowPageJob;
use App\Jobs\Page\StorePageJob;
use App\Jobs\Page\UpdatePageJob;

class PageController extends Controller
{
    public function store(Request $request)
    {
        return $this->dispatch(new StorePageJob($request));
    }

    public function show(Request $request)
    {
        return $this->dispatch(new ShowPageJob($request));
    }

    public function update(Request $request)
    {
        return $this->dispatch(new UpdatePageJob($request));
    }
}

I personally think it would be better if I just try to categories my controllers in folders and separate codes with namespaces .

so

1 - Is using jobs ,like this code an standard way ? if yes what's the benefit of this structure ?

2 - What is the best way for managing structure of large scale projects specially in laravel 5.4 ?



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

catch json response in jquery using ajax without refresh [on hold]

I am missing something...but i don`t know what. I want to make an ajax request using jquery and laravel 5.4. In java script i have this script

My html form is form

The if for checking if the password match don`t work. It goes directly to url and get response from server in browser (plain json)

 return response()->json(['success' => false, 'message' => 'Password don`t match!']);

How to check (on client) if password match? (then do the ajax) How to catch the response and showing in alert? (not plain json in browser) WITHOUT REFRESH???



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

Trying to show comments and files Laravel

In a laravel project, in a controller im trying to show the comments and the files from database

my fuction goes like this

public function show($id)
    {
// with('comments')->
        $shipment = Shipment::with('comments')->where('id','=', $id)->first();
        // $shipment = Shipment::with('files')->where('id','=',$id)->first();

        return response()->json($shipment);



    }

I commented the file row because it was bringing me or the files or the comments, not both, and I need to retrieve the two arrays in the shipment object.

How can I add the files and the comments to shipment?



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

Counting page views with Laravel

I want to implement page view counter in my app. What I've done so far is using this method :

public function showpost($titleslug) {
        $post = Post::where('titleslug','=',$titleslug)->firstOrFail();
        $viewed = Session::get('viewed_post', []);
        if (!in_array($post->id, $viewed)) {
            $post->increment('views');
            Session::push('viewed_post', $post->id);
        }
        return view('posts/show', compact('post', $post));
    }

I retrieve the popular posts list like this :

$popular_posts = Post::orderBy('views', 'desc')->take(10)->get();

However, I'd like to know if there are any better ways to do this ? And with my current method, can I get a list of most viewed posts in the past 24 hours ? That's all and thanks!



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

sql syntax or access voilation

My MySql function keep on giving me syntax error message:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in 
 your SQL syntax; check the manual that corresponds to your MySQL server version 
 for the right syntax to use near 'SELECT SUM(sell_rate) FROM (SELECT 
 COUNT(stock_id)*stock_rate sell_rate 
 FRO' at line 2 (SQL: select 
 SELECT SUM(sell_rate) FROM (SELECT COUNT(stock_id)*stock_rate sell_rate 
 FROM tbl_stock st 
 INNER JOIN tbl_product pdt ON pdt.product_id = st.produck_id 
 WHERE produck_name = 'product_id' lIMIT 6
 GROUP BY stock_id)

  from `tbl_stock`)

I have checked all my brackets and they are all closed i have even executed this on MySQL workbench and it is fine but in Laravel it gives me that error here is my function

private function totalprice( $product_id)
   {
   $selltotal = DB::table('tbl_stock')
   ->select(DB::raw("
    SELECT SUM(sell_rate) FROM (SELECT COUNT(stock_id)*stock_rate sell_rate 
    FROM tbl_stock st 
    INNER JOIN tbl_product pdt ON pdt.product_id = st.produck_id 
        WHERE produck_name = 'product_id' lIMIT 6
    GROUP BY stock_id)

    "))->get();
  return $selltotal;
   }



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

Syntax error: COLUMN isn't in GROUP BY (SQL, Laravel)

I get an error in Laravel 5.4 trying to run the following query:

    return ReferLinkVisit::where('refer_link_id', $this->id)
        ->groupBy('ipaddr')
        ->get()

Error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'database.refer_link_visits.id' isn't in GROUP BY (SQL: select * from `refer_link_visits` where `refer_link_id` = 1 group by `ipaddr`) (View: /resources/views/dashboard/refer/home.blade.php)

Yet I can run the command in phpmyadmin and it will work just fine. I don't get it because I've wrote similar queries a hundred times but for whatever reason this time it just doesn't want to work. I can't figure out what I've done wrong.

Table structure:

enter image description here



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

How to rollback the installation of a laravel package

I tried to install laraAdmin package for laravel on Laravel 5.4. But is failed because it doesn't yet has a support for 5.4. Now am trying to bring back the project at the stage it was before the installation attempt.

Note: I am not using any version control tool like git for this particular project.

Please how can I do that?



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

Laravel 5.4 usage of "Storage::putFile"

I am working with Laravel 5.4 and want to upload a file (let's call it "lorem.ext") to the storage directory (storage/app/) "path/to/file" with a unique file name.

For that I want to use Storage::putFile (http://ift.tt/2tRusQt) which not only stores my file, but also automatically creates a unique file name.

The documentation says to use such:

Storage::putFile('uploadedFile', new File('/path/to/file'));

Using this, I will get the error

FileNotFoundException in File.php line 37: The file "/path/to/file" does not exist

My further thoughts:

I honestly do not know exactly what the signature means and never found a working example from putFile in the web. In the documentation it is not described and looking closer (http://ift.tt/2vfkr3r) there is no information, as well.

What I think it means:

The first parameter "uploadedFile" (or as http://ift.tt/2tRusQt calls it: "photos") will automatically get the file via the ID from the form in the view:

<input type="file" id="uploadedFile" name="uploadedFile">

and there is no need anymore to load it via

request()->file('uploadedFile')

The second parameter "new File('/path/to/file')" (or as http://ift.tt/2tRusQt calls it: "new File('/path/to/photo')") will specify the path in the target storage directory on the server without the file name:

.../storage/app/path/to/file/formerLoremNowUniqueFileName.ext

So complete example where I can upload my lorem.ext and it will get stored on .../storage/app/path/to/file/formerLoremNowUniqueFileName.ext (which does not work):

View:

<form method="POST" action="URL/TO/STORE" enctype="multipart/form-data">
    
    <input type="file" id="uploadedFile" name="uploadedFile">
    <button type="submit" class="btn btn-primary">Upload</button>
</form>

Controller:

public function store() {
    return Storage::putFile('uploadedFile',  new File('/path/to/file'));
}

Can anybody

  1. describe the signature of "putFile" so that I get it? ;-)
  2. tell me why my example is wrong and why I do get this FileNotFoundException?

Thank you!



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

Configure email in aimeos laravel

Hi i'm recently doing a project on an e-commerce site which using laravel that customize on Aimeos however i was stuck in email configuration which i couldn't send email while registering users.

Note that i have configure this in myShop.php and also set cronjobs

'email' => array( 'from-email' => 'demo@aimeos.org', 'from-name' => 'Demo shop', )

crunjobs

          • php /Users/hakfonglim/Documents/laravel/aimeos/aimeos-laravel/myshop/artisan aimeos:jobs "customer/email/account"


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

How to catch "too many attempt" exception in a middleware Laravel 5

I am building my API and I successfuly managed to catch some errors on a middleware I set up around my routes like following :

Route::group(['middleware' => \App\Http\Middleware\ExceptionHandlerMiddleware::class], function() {

    Route::resource('/address', 'AddressController');

    Route::resource('/country', 'CountryController');

    Route::resource('/phone', 'PhoneController');

    Route::resource('/user', 'UserController');
});

The middleware manage to catch the following exceptions :

  • Illuminate\Database\Eloquent\ModelNotFoundException
  • Illuminate\Validation\ValidationException
  • Exception

Which is great. I am also aware of a throttle mecanism that control the number of attempt in a route. So with postman I attacked my route http://localhost:8000/api/user until I get the too many attemp error.

The exception is throwed in the file located at :

/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php

And I also managed to get the type of exception it throws thanks to this forum topic : Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException.

So in the end my middleware looks like this :

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Exception;

class ExceptionHandlerMiddleware
{
    public function handle($request, Closure $next)
    {
        $output = $next($request);

        try {
            if( ! is_null( $output->exception ) ) {
                throw new $output->exception;
            }

            return $output;
        }
        catch( TooManyRequestsHttpException $e ) {
            return response()->json('this string is never showed up', 429);
        }
        catch( ValidationException $e ) {           
            return response()->json('validation error' 400);
        }
        catch( ModelNotFoundException $e ) {            
            return response()->json('not found', 404);
        }
        catch( \Exception $e ) {            
            return response()->json('unknow', 500);
        }
    }
}

You see the line this string is never showed up ? In fact it is never showed up, the original throttle exception from Illuminate always take the front.

QUESTION

How can I properly override the base error in a way that I could possibly (if possible) catch any exception without having to modify the illuminate file (in case of updates...) ?



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

Error in converting relational collection to Json

I trying to get records from 2 tables,

One table is position and another one is items which have parent_id. this is some sample data:

Table: position

title    
----------
admin
user

Table: items

id   |  position  |  title  |  parent_id
-----+------------+---------+------------
1    | admin      | Test    | 0
2    | admin      | Test 2  | 0
3    | admin      | Test 3  | 2
4    | admin      | Test 4  | 3
5    | user       | Test 2  | 0

parent_id in this table refer to parent record in this table.

This is my models relations:

Model: Items

    public function child()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }

    public function children()
    {
        return $this->child()->with('children');
    }

Model: Position

public function pos()
    {
        return $this->hasMany('App\Models\Items', 'position', 'title');
    }

    public function pos_children()
    {
        return $this->pos()->with('children')->where('parent_id', '=', 0);
    }

Now I trying to get all positions with items so I wrote this code in my controller:

NavigationPosition::with('pos_children')->get();

Everything is OK until now and all records will fetch from database but I have problem when I use toJson() method :

NavigationPosition::with('pos_children')->get()->toJson();

I will get this error:

(1/1) BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::getHasActiveAttribute()

What should I do?



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

Laravel, array is undefined?

I have a function like this:

    public function handle()
    {
        News::truncate();
        $client = new Client();
        $crawler = $client->request('GET', 'features');
        $crawler->filter('div[id=content]>.homefeature')->each(function ($node, $key) {
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        if ($image = $node->filter('img')->count () > 0) {
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        $image = $node->filter('img')->image();
        $image_s = $image->getUri();
        $image_s = preg_replace("/thumb_/", "", $image_s);
        $filename = basename($image_s);
        $image_path = ('news-gallery/' . $filename);
        Image::make($image_s)->save(public_path('news-gallery/' . $filename));
        $id = 1+ $key + 1;
        $news = News::where('id', $id)->first();
        // if news is null
        if (!$news) {
            $news = new News();
        }
        $news->title = $title;
        $news->datepublished = $datepublished;
        $news->description = $description;
        $news->link = $link_r;
        $news->image = $image_path;
        $news->save();
        $this->info('Main article ' .$title. ' done succesfully');
    });
    $crawler->filter('div[id=content]>.teaser-50')->each(function ($node, $key) {
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        $image = $node->filter('img')->image();
        $image_s = $image->getUri();
        $image_s = preg_replace("/thumb_/", "", $image_s);
        $filename = basename($image_s);
        $image_path = ('news-gallery/' . $filename);
        Image::make($image_s)->save(public_path('news-gallery/' . $filename));
        //$id = 1+ $key + 1;
        $newsArray[] = [
            'title' => $title,
            'datepublished' => $datepublished,
            'description' => $description,
            'link' => $link_r,
            'image' => $image_path,
            ];       
        $this->info('Scraping done for ' .$title. ' succesfully');
    });
    print_r($newsArray);
    //$news = News::insert($newsArray);
    }
}

So I am trying to put everything into an array before saving it, however I get an error saying that $newsArray is undefined? if I put print_r inside the function, just below it I do get an output. How can this be solved? What I want to do is to loop throught each results as it does now, insert it into an array and later on, bulk insert it to db



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

VueJS + Laravel 5.4 +Phpstorm bootstrap doesnt work

I have a problem with bootatrap when im using vuejs in laravel 5.4 with phpstorm. Bootstrap styles from sass arent working in example on laravel 5.4 with vuejs on starting.

Firstly had a problem with dev in vue. I installed nodejs and ruby. But still Has no bootstrap in there. Anyone got same issue?



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

Larvel 5.0 Intervention Image

Class Intervention\Image\ImageServiceProvider::class not found

I have installed this package using composer and update providers and facaded also.Still this error has shown.Please help



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

Error in adding watermark to large images in Laravel Using Intervention Image

I would like to ask your ideas if what I have gone wrong with the adding of watermark to my images on upload using Intervention/Image in Laravel.

First, I used dropzone to upload multiple files on queue. It worked well according to my preference.

Now, I need to upload at the same time the image with the watermark. I stored the images with watermark to different folder but inline with the folder of original files.

Here is my code for uploading the images:

public function upload(Request $request)
{
    //this upload to original files to the first folder
    $image = $request->file('file');
    $destination = public_path('images/raw');
    imageName = $image->getClientOriginalName();
    $fileType = $image->getMimeType();
    //files are now saved
    $image->move($destination,$imageName);

    //I passed the new destination for watermarked images
    $newD = $destination.'-wmark';

    //I have to check first if the file type is video

    if(strpos($fileType, 'video') === false) {
        $this->makeWaterMark($destination.'/'.$imageName, $newD, $imageName);

    }  
}


public function makeWaterMark($file, $newD, $name)
{

    if(!is_dir($newD)){
        mkdir($newD,0777);
    }

    copy($file, $newD.'/'.$name);

    $newF = $newD.'/'.$name;
    $img = Image::make($newF);
    $img->resize(1850, 1850);
    $img->insert(public_path('images/logo.png'), 'bottom-right', 10, 10); 
    $img->save($newF);
    return $newF; //return value
}

This works with images that has small file sizes, even if I simultaneously upload those images, but if I'm going to upload images that are 3-5mb file size, even only 2 images, I got an internal error. No errors are shown. I don't know why. Is there limitations to resizing or inserting watermarks using Intervention/Image in Laravel.

I really need your help.

Thanks in advance.



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

datatables laravel returned html element as a text

Plesas=e find an attached pictures , The laravel datatables return an html as a text i used a rawColumns and rscapeColumns but not working

Please what a solution and thank you enter image description here



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

How parse data from Carbon Laravel with VUEjs

I return from my backend one Model Object like:

$model = new MyModel();
$meeting->name = "name test n.".rand(0,10000);
$meeting->data = Carbon::NOW();

Now in my fronted created with VueJs, for property data I have:

{ "date": "2017-07-31 08:03:44.000000", "timezone_type": 3, "timezone": "UTC" }

But How Can i parse data from carbon with VueJs with format dd/mm/yyyy ?



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

Custom function in Laravel return NULL but on var_dump is not NULL

I have custom class in laravel 5.4 app which should return hashed secret. The class is

class Hash {

   // Unencrypted secret

   private $secret;

   public function generateSecret(){

       $secret = generateSecretKey();

       $secret_hash = password_hash($secret, PASSWORD_BCRYPT);

       Session::put('secret-hash', $secret_hash);
       $this->secret = $secret;        
   }
}

Then in my controller I have

use Hash;
class UsersController extends BaseController
{
    public function Auth()
    {
        $myhash = new hash();
        $msg = '';

        $myhash->generateSecret();
        $enc = $myhash->encryptSecret($key->key);
        return View::make('users.auth', ['enc'=> $enc]);
    }
     ...
}

var_dump($myhash->generateSecret()); from the controller return NULL

var_dump($secret) in public function generateSecret() return string(15) "866094233422231" string(15) "583375207466239" which is correct.

var_dump($myhash); in UsersController also return correct data

String(15) "008844975703088" object(Hash)#329 (1) 
{ 
     ["secret":"Hash":private]=> string(15) "008844975703088" 
}

Appears that the problem is in controller and generating the hash $myhash->generateSecret();. The function must generate secret(a string) which then is hashed $enc = $myhash->encryptSecret($key->key); and displayed on page.

Any ideas why the function isn't working? I don't know what else I can try.



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

sending mail to mailtrap.io

Hlw, I am using laravel 5.1 I made a contact page in my application. So users can send email. Here I have used mailtrap.io It works when I have created. I mean there were no problem to send mail to mailtrap.io But today, when I was checking this again, It shows me this error.

Swift_TransportException in StreamBuffer.php line 268: Connection could not be established with host mailtrap.io [A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

10060]

I have chacked my .env file with mailtrap.io setting. everything is ok. here is my .env file setting

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=25
MAIL_USERNAME=23cf74ee0552eb
MAIL_PASSWORD=35537e97bbe77d
MAIL_ENCRYPTION=tls

Anyone please help me. Thanks in advance.



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

How to make a link in a view to post route in laravel

I have a post route

Route::post('/filter',SchulMasterController@paginationFilter");

and I want to link to the post route in my view

<li class="chevron_right waves-effect">
<a href="">
<i class="material-icons">chevron_right</i></a>
</li>

but I only know how I can link to GET routes.

Thanks,
Leo



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

dimanche 30 juillet 2017

How to pass PHP array to vue js file from blade format html

i'm working on laravel framework using google map api with vue.js and facebook's graph api with php. i need to get an array of longitude and latitude of that places coming from facebook's graph api to show them on map using google map api. the array of places is coming from a function of php class and graph is forming up in vue.js file, and here i'm facing a problem that how can i get that php array in vue.js so that i would be able to show them(places) on map.

var app = new Vue({

        el: '#app',
        mounted(){
                var self = this;
                this.$on('google.maps:init', function(){
                self.createMap()
        });
        },
  data:{
    lat : ''
  },
        methods: {
                 facebookCheckins : function(){
         var map= new google.maps.Map(document.querySelector('#map'),{
         center: {lat: 35, lng: -85},
          zoom:12
        });
        for (var i = lat.length - 1; i >= 0; i--) {
                
                            var marker = new google.maps.Marker({
                              position: {lat: lat[i]['latitude'] , lng: lat[i]['longitude']},
                              map: map,
                              title:place['name']
                        });
        }
     }
        }
});
<div id="app">
        <h5><?php echo $lat ?></h5>
        <form @submit.prevent="facebookCheckins">
  <!-- **here i'm passing that array in js file** -->
                <input type="hidden" id="lat" v-model="" name="lat_lng">
                <button type="submit">Locate</button>
        </form>
        
        <div id="map"></div>
        </div>
         <script src="http://ift.tt/2agbZVE"></script>
        <script src=""></script>

        <script src="http://ift.tt/2wcJAJ1" async defer></script>

And in Controller // making object of class where facebook graph api code is written $obj=new App\Place(); $results=$obj->searchPlaces(31.55,74.375); $resultsize=count($results); for ($i=0; $i placesInfo($results[$i]['id']); $latitude=$place['location']['latitude']; $longitude=$place['location']['longitude']; $lat_lng[$i]= array('latitude' =>$latitude ,'longitude'=>$longitude );
$lat=json_encode($lat_lng); }

return view('facebook_place_search')->withLat($lat);



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

Laravel observer pattern for keeping two related models in sync

I'm using Laravel 5.4. I have two related eloquent models:

ImageFile and ClipartImage.

ClipartImage contains a belongsTo relationship as follows:

class ClipartImage extends Model
{
    public function image_file()
    {
        return $this->belongsTo(ImageFile::class, 'image_file_id');
    }

    public function promote()
    {
        $this->image_file->promote();
    }
}

On ClipartImage there is a "promote" method which will pass the promote call through to the ImageFile object as it knows how to promote itself.

The problem I'm running into is if things change on the underlying image file, there are a couple of properties on the related ClipartImage which may be affected. In the ImageFile class I could search the database for any related ClipartImages and update the relevant properties, but this doesn't update the ClipartImage instance already loaded and in memory that I am working with, so what's the best way to handle this in Laravel?

In other languages I'm used to I might define a xxxChanged event on the ImageFile class which the ClipartImage could subscribe to so it can update/refresh itself when required.

I guess I'm in need of some sort of Observer pattern but in Laravel these things seem to be handled at the static/class level not for individual object instances - ie I could create an observer class that looked for any changes to ImageFile models, but that isn't going to help me refresh or update my existing ClipartImage object is it?

If I was going to try and roll something custom - eg just have a property on ImageFile for currentClipartImageInstance so the ImageFile could call back to the ClipartImage instance to refresh it, I wasn't clear where I would add the hook - I thought of defining a mutator so I could add the hook after the relationship was set but I don't think that would work -eg if associate etc was used to establish a relationship.

Any advice on the normal way to handle this welcome I'm still fairly new to Laravel and worried I'm missing something simple here.

Edit: Please note that while I've distilled this down to a single promote method to illustrate the point, there's a bunch of interaction between ClipartImage and the underlying file class and it's not obvious from the point of view of ClipartImage when it may need to refresh or make changes to itself, mostly it won't as I've tried to segregate things as much as I can into their respective classes - reading back the example it seemed like the obvious solution might be to do some sort of refresh after the promote call, but I'm looking for something a bit more generic as there are lots of such calls.



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

Loading url with slug in laravel 5.4

I realize that there are similar questions but non of them is helped me so far. So I'm trying to make URL's to load with slug. In RouteServiceProvider I have added this

public function boot()
{
    //
    parent::boot();

    Route::bind('/', function($slug) {
        return Pages::where('slug', $slug)->first();
    });
}

In my routes this

Route::get('/{page}', [
    'uses' => 'HomeController@page',
    'as' => 'page'
]);

The button in the view

<a href=""></a>

And my model

class Pages extends Eloquent {

    protected $fillable = ['page_title', 'slug', 'page_body'];
    protected $table = 'pages';
    protected $primaryKey = 'page_id';

    public $timestamps = false;

}

When I click on the link to open the page the error is

NotFoundHttpException No query results for model [App\Pages].

I have added use App\Pages to files too.

I can't see what is wrong here?



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

Date picker in Safari using Laravel collective

I'm using Laravel 5.4 and especially Laravel collective to create forms. The type date is working great on chrome and safari mobile but in Safari for Mac and Firefox it shows only a blank field which doesn't allow the user to add a date in the correct format.

Do you have any idea how to fix this issue ?

Thanks ;)



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

GuzzleHttp:how can I save cookies from a POST response and use it in the next POST?

I'm using Guzzle to login my API site, and in the moment Im login with the right credentials, I get back a cookie with a RefreshToken to send it in the next call, here is my simple (and working well) code:

$client = new Client(array(
            'cookies' => true
        ));


        $response = $client->request('POST', 'http://myapi.com/login', [
            'timeout' => 30,
            'form_params' => [
                'email' => $request->get('email'),
                'password' => $request->get('password'),
            ]
        ]);

and I get back the right response with a cookie, I can see the cookie by using:

$newCookies = $response->getHeader('set-cookie');

now, I need to use this cookie in the next calls, and I know Guzzle can save the cookie for me and send it automatically (or not) in the next call using a "CookieJar" or "SessionCookieJar", I have tried to use it but I do not see the cookie in the 'jar', here is what I have done:

$cookieJar = new SessionCookieJar('SESSION_STORAGE', true);

        $client = new Client([
          'cookies' => $cookieJar
        ]);

        $response = $client->request ....

but, when I get the cookie back from the POST, I can see it only by using:

$newCookies = $response->getHeader('set-cookie');

and its not in the cookieJar, so it won't send it in the next call.. what am I missing here?

Thank you!



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

Laravel 5 save ids from table in one column

How will you be able to insert ids from other table to one column on another table?

Ex:

table_a a_id a_name

table_b b_id b_car a_id

Is it possible to save multiple ids to table_b.a_id from table_a.a_id in Laravel? I think this has to be related in hasMany but I'm not too familiar in laravel. Thank you.



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

Laravel 5.4 - Site-wide authentication checking

I'm looking to find the best way to implement site-wide authentication checking in Laravel 5.4

I'm building a website that has a growing number of pages that check for rows in a database assigned to a user. If someone visits a page on the site that carries out this function, and they are not logged in, Laravel will give

"Trying to get property of non-object"

and display its error page.

I need to remove all Laravel error pages from my project, to clean it up, and I'm starting with these errors:

Current solution:

My current solution is that wherever a route makes these checks in a controller, I wrap it in

if (Auth::check()) {

I'm wondering if there is a better solution other than wrapping all such code in this?

Edit I need to go and learn how middleware works.



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

Laravel 5.4 Notification Broadcasting

I've set it up with the database, and everything is inserted correctly there. and I am listening correctly with Laravel Echo, and thats being recorded on Pusher, but all my notifications etc are not received by pusher? Can anyone see something I am doing wrong?

My Notification Class

<?php

namespace App\Notifications;
use Carbon\Carbon;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;

use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class RepliedToThread extends Notification 
{
    use Queueable;
    public $thread;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($thread)
    {
        $this->thread=$thread;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database','broadcast'];
    }

  
    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    // public function toDatabase($notifiable)
    // {
    //     return [
    //            'thread' => $this->thread, 
    //            'repliedToTime' =>Carbon::now(),
    //            'user'=>auth()->user()


    //     ];
    // }
    
    // public function toBroadcast($notifiable)
    // {
    //     return new BroadcastMessage([
    //                 'thread' => $this->thread, 
    //                'repliedToTime' =>Carbon::now(),
    //                'user'=>auth()->user(),
    //     ]);
    // }
    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
                    'thread' => $this->thread, 
                   'repliedToTime' =>Carbon::now(),
                   'user'=>auth()->user(),
        ];
    }
}

broadcating.php

although when this is fired it gets sent to the database but not to pusher. Everything for pusher is setup in my .env file.

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "redis", "log", "null"
    |
    */

    'default' => "pusher",

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => 'ap1',
                'encrypted' => true
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

.env file

BROADCAST_DRIVER="pusher"
PUSHER_KEY="public_key"
PUSHER_SECRET="secret_key"
PUSHER_APP_ID=app_id

bootstrap.js

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap-sass');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: http://ift.tt/2hex2P1');
}

// window.axios.defaults.headers.common = {
//     // 'X-CSRF-TOKEN': window.Laravel.csrfToken, <-- Comment it out (if you are extending layouts.app file, you won't require this.)
//     'X-Requested-With': 'XMLHttpRequest'
// };
import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');
window.Echo = new Echo({
        
    broadcaster: 'pusher',
    key: '################',
    cluster: 'ap1',
    encrypted : true
});
/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//      authEndpoint : 'http://localhost/forum_web/public/broadcasting/auth',

//     broadcaster: 'pusher',
//     key: '9964dcd35bae49f32d6c',
//     cluster: 'eu',
//     encrypted: true,
// });
iam used vue2

notification.vue

<template>
    <li class="dropdown" @click="markNotificationAsRead">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
            <span class="glyphicon glyphicon-globe"></span> Notifications <span
                class="badge alert-danger"></span>
        </a>

        <ul class="dropdown-menu" role="menu">
            <li>
                <notification-item v-for="unread in unreadNotifications" :unread="unread"></notification-item>
            </li>
        </ul>
    </li>
</template>

<script>
    import NotificationItem from './NotificationItem.vue';
    export default {
        props: ['unreads', 'userid'],
        components: {NotificationItem},
        data(){
            return {
                unreadNotifications: this.unreads
            }
        },
        methods: {
            markNotificationAsRead() {
                if (this.unreadNotifications.length) {
                    axios.get('markAsRead');
                }
            }
        },
        mounted() {
            console.log('Component mounted. asd 1111');
            Echo.private('App.User.' + this.userid)
                .notification((notification) => {
                    console.log(notification);
                    
                });

        }
    }
</script>


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

How to pass model data inside foreach loop to views using laravel5

I have a foreach loop where each time certain value is matched and then it related records is fetched

 foreach($results as $result){
    // Value may be 1,2,3 etc
    if($result->id == $value){
       $users = User::whereId($value)->get();
    }
  }
  return view('winners.winners',compact('users'));

Now how to pass all users records to the view? Currently it only fetches the first record!



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

Laravel 5.2: passing session in a where clause

I am using Laravel 5.2 and trying to pass an existing session in a where clause:

The session called currentOrderReference works as expected and its value is: 31GENERND2342
If I try to get the customer_id using following query, the query does not return any customer_id:

$ref = session()->get('currentOrderReference');
Order_reference::select('customer_id')->where('reference',$ref)->first();

But if I replace the var $ref with its value like this, then it works

Order_reference::select('customer_id')->where('reference','31GENERND2342')->first();

What I am doing wrong in the first query?



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

unable to display table data in blade file in Laravel

Need display table data in laravel on show.blade.php file it is generated from TaskController.php

public function index()
{
    $tasks = Task::all();
return view('tasks.index')->with('tasks', $tasks);

}

this is index.blade.php

@if(isset($tasks))

@foreach ($tasks as $task)

<h1></h1>

@endforeach

@endif

include this index with file to show.blade.php

@include('tasks.index')

but not generate any results???? No any error??? how to fix this



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

Mailchimp package not adding email address to list

I am using the following laravel package for my newsletters:

laravel-newsletter.

I have the following code in my newsletterController.php:

public function index() {
    Newsletter::subscribe('rincewind@discworld.com', ['FNAME'=>'Goti', 'LNAME'=>'Loki'], 'test');
    return 'Ola !';
}

Now when i go to: /newsletter in my application i see Ola !, but when i open my mailchimp dashboard i see don't see rincewind@discworld.com added to the list of emails for the list test.

I also tried the following method of the mailchimp package:

return Newsletter::isSubscribed('codedevakagautam@gmail.com');

This email address already exists in the list test, i get the following error:

Call to undefined method Spatie\Newsletter\Newsletter::isSubscribed() 

What am i doing wrong ? Can somebody please guide me.



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

Laravel show number of requests for each meeting

I have these tables: users, meetings, requests:

users
id
name

meetings
id
name

requests
id
user_id
meeting_id
accepted

each meeting has number of requests from users and request table has accepted column, I want to show a list of user's meetings and number of requests for each meeting user meetings:

requests    meeting name    created_at
10          dummy meeting   10/10/2010

Meeting model

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

Requests model

public function meeting()
    {
        return $this->belongsTo('App\Meeting');
    }

How this can be done?



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

Laravel JQuery AJAX POST get data

I have a code:

var bet = {
tournament: '',
    bo: '1',
    bet_team: '2',
    betted: '3',
    potential: '4',
    percent: '5'
};
$.ajax({
            type: 'POST',
            url: '/api/makeBet/',
            data: bet,
            contentType: 'application/json',
            dataType: 'json',
            success: function(data) {
                if(data.error) {
                    sweetAlert("Oops...", data.data, "error");
                } else {
                    sweetAlert("Success!", data.data, "success");
                }
            },
            error: function(html, status) {
                console.log(html.responseText);
                console.log(status);
            }
        });

But when I'm trying to get $request->tournament or something else, I'm getting nothing.



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

samedi 29 juillet 2017

how to put URL inside of laravel blade

I have database structure like Book & download link ..

$book= new Book();
$book->name = $request->Input(['name']);
$book->download_link = $request->Input(['download_link']); // eg. http://ift.tt/2vi6OB3
$book->save();

now if i want to give this in blade page ..like download link..how do i put in href tag so that it will redirect the user to that page?

<a href=""></a>
// This doesn't work



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

Populating Users table with foreign key constraint onto another table in Laravel 5.4

I added a column account_id with foreign key constraint onto the accounts table to my users table.

For the registration process I now want the email to be first inserted into the accounts table. Then I want to populate the users table with the account_id and all other registration information.

My RegisterController.php looks like this:

   protected function create(array $data)
   {
      $account = Account::create([
            'email' => $data['email'],

        ]);

        return User::create([
//          'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'account_id' => $accounts['id']
        ]);

    }

This gives me the error Class 'App\Http\Controllers\Auth\Account' not found when creating a new user.

I'm new to Laravel and am a bit lost here. Any pointers would be great!



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

php laravel route::pattern() issue

I have the same issue as this guy:

Laravel route not matching pattern

Here's my offending pattern:

Route::pattern('uuId', '/^\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}?$/i');

If I comment this line out, my request works great, so I'm positive it's related to this pattern. Like the linked to OP, I can confirm my regex is good:

http://ift.tt/2hctpZL

The issue here is probably that I don't know regex well, I'm usually one to just google if I need something specific where regex is concerned.

I removed the opening slash and it didn't work, removed the opening and ending slash and that too also didn't work. I'm sure it's my understanding of regex here that is the issue, but no matter how I play around with it I can't seem to get it work.

If anyone knows how to make that pattern work in Laravel for me, that would sure be great. Thanks!



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

How to ignore ckeditor's html tags in laravel for email function?

I am trying to send email from my laravel application, and there is a body field which is using ckeditor.The problem what am i facing is like all the html tags are entering in my email without changing the effectsenter image description here

Is there anyway to solve this problem? Any help would be appreciated.



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

laravel pagination not working 5.4

Pagination not working links displaying fine.

when I clicked on 2nd-page same 1st-page items only showing even, clicked on any page first results only showing but url changing as per the click results of items not changing.

Please check the below code controller and view file code given below.

Controller:

  public function index(Request $request)
        {
            $keyword = $request->get('search');
            $perPage = 10;

            if (!empty($keyword)) {
                $products = Product::where('pname', 'LIKE', "%$keyword%")
                    ->orWhere('pdescription', 'LIKE', "%$keyword%")
                    ->orWhere('price', 'LIKE', "%$keyword%")
                    ->orWhere('pcategory', 'LIKE', "%$keyword%")
                    ->orWhere('brandname', 'LIKE', "%$keyword%")
                    ->orWhere('pcategoryslug', 'LIKE', "%$keyword%")
                    ->orWhere('productslug', 'LIKE', "%$keyword%")
                    ->orWhere('pimg', 'LIKE', "%$keyword%")
                    ->orWhere('pimg1', 'LIKE', "%$keyword%")
                    ->orWhere('pimg2', 'LIKE', "%$keyword%")
                    ->orWhere('pimg3', 'LIKE', "%$keyword%")
                    ->orWhere('pimg4', 'LIKE', "%$keyword%")
                    ->orWhere('pimg5', 'LIKE', "%$keyword%")
                    ->orWhere('partner_id', 'LIKE', "%$keyword%")
                    ->orWhere('status', 'LIKE', "%$keyword%")
                    ->paginate($perPage);
            } else {
              $products = Product::where(['partner_id'=>\App\Partner::id()])->orderBy('id','desc')->paginate(10);
                   // $products =  DB::table('products')->select('products.id as id','pname','pdescription','path','pcategory','price')->where(['products.partner_id'=>\App\Partner::id()])->join('product_images', 'product_images.product_id', '=', 'product_images.product_id')->groupBy('product_images.product_id')->paginate($perPage);//toSql(); //p
            }
           return view('admin.products.index',['products'=>$products]);
        }

view: 

  <div class="table-responsive">
                            <table class="table table-borderless">
                                <thead>
                                    <tr>
                                        <th>ID</th><th>Image</th><th>Name</th><th>Description</th><th>Category</th><th>Price</th><th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php $i = 1; ?>
                                @foreach($products as $item)
                                    <tr>
                                        <td><?= $i++; ?></td>
                                        <td><img src="" width="50" /></td>
                                        <td></td>
                                        <td></td>
                                        <td></td>
                                        <td>Rs </td>

                                        <td>
                                            <a href="" title="View Product"><button class="btn btn-info btn-xs"><i class="fa fa-eye" aria-hidden="true"></i> View</button></a>
                                            <a href="" title="Edit Product"><button class="btn btn-primary btn-xs"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></a>
                                            {!! Form::open([
                                                'method'=>'DELETE',
                                                'url' => ['/admin/products', $item->id],
                                                'style' => 'display:inline'
                                            ]) !!}
                                                {!! Form::button('<i class="fa fa-trash-o" aria-hidden="true"></i> Delete', array(
                                                        'type' => 'submit',
                                                        'class' => 'btn btn-danger btn-xs',
                                                        'title' => 'Delete Product',
                                                        'onclick'=>'return confirm("Confirm delete?")'
                                                )) !!}
                                            {!! Form::close() !!}
                                        </td>

                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
      <div class="pagination-wrapper"> {!! $products->appends(['search' => Request::get('search')])->render() !!} </div>

{!! $products->render() !!}
                        </div> 



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

$(selector).each on table rows w/ Laravel

this is my first question here and I've been searching for a long time about this, also I'm more than a newbie on jQuery and JavaScript in general, but I need it for very small tasks right now so I just got into it without a very deep knowledge of it.

I'm using Laravel 5.4, and I have a table which body is made of a loop on rows because I need it to show results from database, not that it matters, but just for the sake of explaining. I gave an id to an icon that if clicked it will perform some actions, first of all rendering a confirm message and then deleting the row if yes is clicked.

The problem is that I can make that rendered if the first row's icon is clicked, but not for the others. I tried the each method but it seems that's not working, and probably I misread the documentation or I'm not understanding its usage

My code for that is really simple (not performing the delete task):

$('document').ready(function(){
    $('#delete').each(function(){
        $(this).click(function(){
            return!! confirm("Are you sure you want to delete this?");
        });
    });
});

I just want to make the confirm box appear for every icon I click on!

Thanks in advance! If you need me to update the question with some more information please tell me!



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

@if is not working in my blade view laravel

code inside the if statement is not changing anything like i want to check if user is logged in then show his name on header but its not doing so..plus if statemet is not changing colour when i view it in sublime text.

@if (Auth::check())
    <ul class="nav pull-right">
        <li class="dropdown">
            <a data-toggle="dropdown" class="dropdown-toggle" href="#">
                <i class="fa fa-user"></i> 
                
                <b class="caret"></b>
            </a>
  <ul class="dropdown-menu">
                <li><a href="">Logout</a></li>
            </ul>                       
        </li>
    </ul>
    @endif



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

No Page Available - Laravel 5.2

I downloaded CMS project from github, Laravel version 5.2. I installed the composer in the folder and change the database info in .env file and the project working fine.

But only the home route is working, the rest of the routes giving me "Opps no page avaible"

The blades files are fine only the routes not working!

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
  return view('welcome');
});

Route::auth();

Route::get('/home', 'HomeController@index');

Route::get('/post/{id}', ['as' => 'home.post', 'uses' => 'AdminPostsController@post']);

Route::group(['middleware' => 'admin'], function () {

  Route::get('/admin', ['as' => 'admin.index', function () {
    return view('admin.index');
  }]);

  Route::resource('admin/users', 'AdminUsersController');

  Route::resource('admin/posts', 'AdminPostsController');

  Route::resource('admin/categories', 'AdminCategoriesController');

  Route::resource('admin/medias', 'AdminMediasController');

  Route::resource('admin/comments', 'PostCommentsController');

  Route::resource('admin/comment/replies', 'CommentRepliesController');


});

Route::group(['middleware' => 'auth'], function () {

  Route::post('comment/reply', 'CommentRepliesController@createReply');

});



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

Create frontend(User) and Backend(Admin User) module with its custom authentication forms

I am new in Laravel, I have just started to learn.

I am trying to develop the one App that have the Fontend and Backend modules. As per the requirements this both modules should be accessible for the authorized users only.

I have created the two tables, 'User' for the frontend user authentication and 'admin_user' for the backend user authentication.

Admin users should be validate in the 'admin_users' table and Fontend users validate in the 'users' table

I read the docs and see that we can implement it using the custom gaurd but I did not understand it clearly.

Any hints how I can start to develop? or Is there any app that has the same flow I mentioned?

Thanks



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

Optimize Eloquent query

I have the following eloquent relation

User Model

public function supplies()
{
    return $this->hasMany('App\Supply', 'employee');
}

Supply Model

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


    public function projects()
    {
        return $this->belongsTo('App\Project', 'project');
    }

Project Model

public function supplies()
{
    return $this->hasMany('App\Supply', 'project');
}

I try to get all supplies per year on projects with the following query

$supplies = Project::with('supplies')->whereHas('supplies', function ($query){
           $query->with('user.skills')->where('deleted', 0)->whereIn('supply_status', [1,2])->whereYear('time_from', 2017);
        })->orderBy('title')->get();

supplies table has lot of entries and I have memory limit problems. How can I optimize to get the best result?



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

Query with two laravel models and return result

I have two models, User and Post

Relationship: post belongsTo user and user hasMany post

In my controller I have a public function which has:

$users = User::orderBy('is_ban', 'desc')->paginate(10);
$posts = Post::orderBy('created_at', 'desc')->paginate(10);

Which is working as expected. I also have one column in users table `is_ban' It's of boolean type.

I am looking for a query which will return the following:

Only get post which has been made by the user which has is_ban=false



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

Laravel job management application

I want to create an application which include 4 or 5 type of users like job creator, design section staff, printing section staff etc. If a new job created it must notified to design section. If the design is over it must notify the printing. Can anyone suggest me how to do that kind of application in professional way.



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

Laravel's Seeder not able to insert data into Multi Level relationship

I have a base table named "Projects" And I have another table named "Project Blocks".

I have defined the relationship for projects to Project block as one to many. The Relationship is defined in this way :

namespace App;
use Illuminate\Database\Eloquent\Model;
class Projects extends Model
{
    public function projectblocks(){
        return $this->hasMany('App\ProjectBlocks','project_id','id');
    }
}

I also have one table Named "Project Units" which has realtionship with project block table:

namespace App;
use Illuminate\Database\Eloquent\Model;
class ProjectBlocks extends Model
{
    public function projects(){
        return $this->belongsTo('App\Projects','project_id','id');
    }

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

I have also defined the table structure inside ModelFactory :

$factory->define(App\Projects::class, function (Faker\Generator $faker) {    
    return [
        'name' => $faker->sentence(5),
        ...//All other required fields               
    ];
});

And

$factory->define(App\ProjectBlocks::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->sentence(5),
        ... //All other fields comes here  
    ];
});

And for Project Units :

$factory->define(App\ProjectUnits::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->sentence(5),
        ...//Other fields              
    ];
});

Now When I try to seed the above tables I am getting errors :

This is the code to seed the table:

use Illuminate\Database\Seeder;
class ProjectsTableSeeder extends Seeder
{
    public function run()
    {    
        factory(App\Projects::class, 20)->create()->each(function($u) {             
            $u->projectblocks()->save(factory(App\ProjectBlocks::class)->make()->each(function($v) {                
                $v->projectunits()->save(factory(App\ProjectUnits::class)->create());               
            })
            );//This is line number XXXXXX          
        });
    }
}

I am getting the following error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\Has
OneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model
, boolean given, called in /var/www/html/seederExample/database/seeds/Proje
ctsTableSeeder.php on line XXXXXX

Please Help me to know where I am making a mistake/s.

In case if more code is needed then please comment so that I can add the code.



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

Best join to get all values

I have table ads and it relation to categories,images,boost,meta table.How to join all and get values with DB Query Builder or Sql statement

Database ERD



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

192.168.13.11 is currently unable to handle this request. HTTP ERROR 500 in laravel

it's work fine in my local environment when I upload it in to the server I can access the home page but when I submit the form it throw the following error

This page isn’t working

192.168.13.11 is currently unable to handle this request.
HTTP ERROR 500

and also I can access the route when I manually write in browser header, but cant access when submit the form



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

category and category's items laravel 5

I've a small website that offers courses each course has lessons so course as category and lesson as item after user log in will appear all courses , when click on a course I wanna go to all lessons for that course.



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

Mysql - Get count of rows from table with offset

I am working on laravel project. I want to get total number of rows from table with offset.Like how many records are there after skipping first 10 records. I am trying to get this by,

$count = Post::skip(10)->count();

But it gives me mysql syntax error. It would be nice if you can even help me with raw mysql query. Thanks!



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

vendredi 28 juillet 2017

Laravel 5: How can I load database values into the config/services.php file?

I have a multi-tenant app I'm working on and while adding the socialite package, I tried to load the custom facebook client_id and client_secret for the specific website from the database. I can't really use the env variables because each site will have it's own custom facebook keys.

It seems you can really call a model's method on the config/services.php file because it might not have been loaded yet. I've tried going through the request lifecycle docs to resolve this to no avail.

I've also tried to create a service provider to get the value from my Business model's method and set it as a constant but still, by the time it's available in the app, the config/services.php file has been loaded.

Here's where I want the database value available:

config/services.php

'facebook' => [
  'client_id' => \App\Business::getAppKeys()->fb_client_id,
  'client_secret' => 'your‐fb‐app‐secret',
  'redirect' => 'http://your‐callback‐url',
],

Error:

Fatal error: Call to a member function connection() on null



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

Laravel 5.4 : Email cannot be sent from online server

I want to sent email to user when he first create an account. This works fine on localhost (I am using mailtrap.io for sending emails from localhost), but when I tried it on online server with my real email id, it does not work.

This is .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.easyname.com
MAIL_PORT=465
MAIL_USERNAME=no_reply@mydomain.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=null

This is my config/mail.php file

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'smtp'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.easyname.com'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 465),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'no_reply@mydomain.com'),
        'name' => env('MAIL_FROM_NAME', 'My name'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

This is my controller function:

$data =['company_name'=>$company_name,'login_email'=>$login_email,'password'=>$plain_password];

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

$message->to($data['login_email']);
$message->subject('Please verify your email address to get started');

});

return redirect()->back()->with('success','Thank you');  



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

LARAVEL 5.4: PostTooLargeException in ValidatePostSize.php (line 24)

I am currently developing an app with Laravel 5.4. I am using xampp and changed the php.ini, php.ini-development and php.ini-production files with the following configurations

post_max_size = 100M

upload_max_filesize = 200M

memory_limit = 128M

I restarted Apache and my laravel development server but still, I get the error

Warning: POST Content-Length of 14253688 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

PostTooLargeException in ValidatePostSize.php (line 24)

I even restarted my PC and still not working. Am I missing something here?

Thanks



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

Laravel Passport Authentication Issues: Always returns unauthenticated

After looking through dozens of answers, I still can't find a solution to his issue.

Problem

Every time I make an authenticated request, the response is {"error":"Unauthenticated."}

Routes

Here are the routes I've been testing with.

use Illuminate\Http\Request;
use Laravel\Passport\Http\Middleware\CheckClientCredentials;

Route::get('/test', function () {
    return 'Hello World';
})->middleware('auth:api');

Route::middleware('auth:api')->get('/test2', function (Request $request) {
    return 'Hello World';
});

Setup

I set this project up as the tutorial instructed, and used the PHP artisan commands to construct my database. I then began to use Postman test it.

The token is acquired using a grant_type: password, client credentials, and user credentials. A "Bearer " . $token type is then granted.

What I've Done and Tested

I've checked the .htaccess, token expiration date, namespaces, and other common errors. I setup a test function to check my header information. The results are posted below. For some reason, the issue persists. There also aren't any actual errors... No error.log updates, just a response from the API letting me know the user is not authenticated.

 array:12 [
    "cookie" => array:1 [
        0 => "XSRF-TOKEN=eyJpdiI6IkwrNGxLOGVtc1M1Y2lYeUMraldTK3c9PSIsInZhbHVlIjoibHRzdVo3bFVJOFhuMDJvZ3RoNEYxK1NsdmhRenZkbmp5b2xuYXVzWTdIUGJ2WGFUbXBiK1JFQ0VNSVlNbjdIbHVmcndmKzBaMzVJbGkxelZFdllhM0E9PSIsIm1hYyI6ImZhMDJjZDIwNDgxMTRkMDdjYTBkYmMwODc4YzQ4ZmM3OGFkZTI3NzY1ZDA5NTAyODhkYjRlNTY1OGUyMTYyNGEifQ%3D%3D;  laravel_session=eyJpdiI6Im5hTnVLS3cyc1BzQldudkN2bFNcLzZRPT0iLCJ2YWx1ZSI6IjIwXC8yRkM3Sk4rWkg0ZFFlaG9RYVErc2ZJT0taSHoxOTU3UVpxejdPZ2MzcHBSc2FCd1NweEZwU2kzQXUxZ1VCVmY1dzZIZldFb2J5QXkwMFwvZmpId1E9PSIsIm1hYyI6ImQxZDIzOGQ0NzllOTg4NmZmZDk2NGI1NDNhMzcwNmI1MWE2MzY0YWIzZTgxZjYzOTAxYjhlMWQ1ZTExNzBiMTEifQ%3D%3D"
    ]
    "accept-language" => array:1 [
        0 => "en-US,en;q=0.8,fr;q=0.6"
    ]
    "accept-encoding" => array:1 [
        0 => "gzip, deflate, sdch"
    ]
    "postman-token" => array:1 [
        0 => "864e4343-e8f1-2efd-1a75-11660313ba3d"
    ]
    "authorization" => array:1 [
        0 => "Bearer 0dea6edd3f655463c4e19cf26ef10755bcfbff5dcdbe44cd44c1d7a84c250c359c65f064737752e6"
    ]
    "cache-control" => array:1 [
        0 => "no-cache"
    ]
    "accept" => array:1 [
        0 => "application/json"
    ]
    "connection" => array:1 [
        0 => "close"
    ]
    "x-http-proto" => array:1 [
        0 => "HTTP/1.1"
    ]
]

Suspicions

At this point, I think I just must be using some of the tools wrong. I'm hoping it is a simple mistake, but I'm just completely at a loss as to what it could be.



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

Laravel 5.4 : Cannot connect to database on online server

I have just uploaded a Laravel project to a web server but it cannot be connected to the database. I have imported the database to phpmyadmin, and have also set the .env and config/database.php file. When I run the page, it still shows me my localhost database settings (username, password, database etc).

This is my .env file

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:qvuzPrZW3awGcn8etObsyAT7SaKRfgr6AHfpnUPfygE=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://findajob.af/

DB_CONNECTION=mysql
DB_HOST=e73573-mysql.services.easyname.eu
DB_PORT=3306
DB_DATABASE=database_name_on_server
DB_USERNAME=username_on_server
DB_PASSWORD=password_on_server

This is my config/database.php file

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'e73573-mysql.services.easyname.eu'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'database_name_on_server'),
            'username' => env('DB_USERNAME', 'username_on_server'),
            'password' => env('DB_PASSWORD', 'password_on_server'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

When I load the page, it gives me following errors:

QueryException in Connection.php line 647:
SQLSTATE[HY000] [2002] Connection refused (SQL: )

And

1. in Connector.php line 68
2. at PDO->__construct('mysql:host=127.0.0.1;port=3306;dbname=databasename_on_localhost', 'localhost_username', 'localhost_password', array(0, 2, 0, false, false)) in Connector.php line 68



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

how config default.conf in nginx 1.13.3 for laravel 5.x

in nginx befor we change /etc/nginx/sites-available/default to

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/laravel/public;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name <Your Domain name / Public IP Address>;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ /index.php?$query_string;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }
    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
}

but in nginx 1.13.3 how we can place this changes?



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

Laravel queues storing the data in jobs table but not sending the queues emails on server

4 Queue and i have installed supervisor on Ubuntu so that i can run queue:work command on Ubuntu as a service 24 h so that i can send emails to user using email Queue.

for that i have created a file a file in

/etc/supervisor/conf.d

to monitor the process queue:work.

here is my file

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/laravel/artisan queue:work database --sleep=3 --tries=3
autostart=true
autorestart=true
user=ubuntu
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/html/laravel/storage/logs/laravel-worker.log

and here is my laravel Mail Queue code

Mail::to($email)->queue(new SubscriberEmail($name));

when i run this code the laravel store the data in jobs table but don't send the emails to users

i have also checked the failed jobs table but their is no data in that table.

i have run this command on server

sudo supervisorctl status

it shows me this detail

laravel-worker:laravel-worker_00 FATAL Exited too quickly (process log may have details)

laravel-worker:laravel-worker_01 FATAL Exited too quickly (process log may have details)

laravel-worker:laravel-worker_02 FATAL Exited too quickly (process log may have details)

laravel-worker:laravel-worker_03 FATAL Exited too quickly (process log may have details)

i have gone to logs folder but their no log file has been generated.

Kindly help me on this issue please.

Thanks



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

How to use two foreachs in laravel?

I have a category table, it is organized by 'parent_id' and 'categoryid'. I need to organize it in a list, where I group the parent class with the daughter class.

I created this code.

In the controller I get the value of the categories.

public function index()
    {
      $cat1 = Category::where('erp_parentid', '=', 0)->get();
      foreach($cat1 as $categoria1){
        $cat2 = Category::where('erp_parentid', '=', $categoria1->erp_categoryid)->get();
        return view('admin.categories')->with('cat1', $cat1)->with('cat2', $cat2);
      }
    }

$cat2 is the child category, I get its values through the categoryid of the parent category.

But when I pass the values to the view, all parent categories take the same value as the first.

enter image description here I used that code to display the values in the view:

<div class="container">
  <div class="row">
    <ul class="list-group">
      @foreach($cat1 as $value)
      <a data-toggle="collapse" data-target="#catfilha"><li class="list-group-item"></li></a>
      <ul id="catfilha" class="collapse">
        @foreach($cat2 as $value2)
        <li></li>
        @endforeach
      </ul>
      @endforeach
    </ul>
  </div>
</div>

I searched for similar cases here on the site, but found no resemblance, any suggestions? Thank you in advance.



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

can laravel route return non www url?

is there way to return Laravel5 route parameter URL without WWW in start ?

I know its work and return full URL with WWW but I want to use this in Laravel5 and it return non WWW URL

route('routeName', ['id' => 1]); //return with www



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

What the variable names/references to get variables from withInput() in the view?

The first controller has his inputs from a request->all() and it calls another controller method using withInputs. To fill the form the variables works well, but I need make a decision if one of the inputs variables already is filled. How should I reference this variable?



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

Error in accessing Class after Package install in Laravel

I Downloaded a Package known as Laravel Shopping Cart darryldecode/cart:~3.0

According to Instruction I have made changes to app.php

1 - Open config/app.php and add this line to your Service Providers Array

Darryldecode\Cart\CartServiceProvider::class

2 - Open config/app.php and add this line to your Aliases

'Cart' => Darryldecode\Cart\Facades\CartFacade::class

Now Whenever i try to access the class like shown below

Cart::add(455, 'Sample Item', 100.99, 2, array());

It gives an error saying Class Cart not Found, I have cleared the cache & views file also, but still no luck.



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

laravel socialite get user informations

I can get user's informations name, gender, etc, but when i try to access user's birthday login doesn't work, this is my code for LoginController

public function redirectToProvider()
    {
        return Socialite::driver('facebook')->fields([
            'first_name', 'last_name', 'email', 'gender', 'birthday'
        ])->scopes([
            'email', 'user_birthday'
        ])->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return Response
     */
    public function handleProviderCallback()
    {
        try
        {
            $facebook_user = Socialite::driver('facebook')->fields([
                'first_name', 'last_name', 'email', 'gender', 'birthday'
            ])->scopes([
                'email', 'user_birthday'
            ])->user();
            // echo $facebook_user->getAvatar();
// this returns the data but when i try to access
// $facebook_user->user['birthday'] it doesnt give any error or login
            // dd($facebook_user->user['birthday']);
            $facebook_user_id = $facebook_user->getId(); // unique facebook user id
            $user = User::where('facebook_user_id', $facebook_user_id)->first();
            // dd($user);
            if (!$user)
            {
                // dd($facebook_user->avatar);
                $user = new User;
                $user->facebook_user_id = $facebook_user_id;
                $user->name = $facebook_user->getName();
                $user->avatar = $facebook_user->getAvatar();
                $user->email = $facebook_user->getEmail();
                $user->gender = $facebook_user->user['gender'];

                // $user->birthday = $facebook_user->user['birthday'];
                // dd($user);
                $user->save();
                auth()->login($user);
                return redirect('/location');
            }
            else
            auth()->login($user);
        }
        return redirect('/location');
    }

and I want to access more informations like users hometown, i added fields and scopes but it doesn't give any error, just returns to login page



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