Showing posts with label Laravel 5. Show all posts
Showing posts with label Laravel 5. Show all posts

Monday, February 27, 2017

Laravel PHP5 Input:All() Malformed Array With Undefined Offset

really simple question/task just have some sort of error somewhere that I can't figure out.

So I am trying to do a post request from a chrome extension (using jquery $.ajax) to a Laravel application.

Everything works except Laravel is not handling POST request payload well.

My ajax:

 $.ajax
    ({
        type: "POST",
        url: 'http://ift.tt/2mynDjK',
        dataType: 'json',
        //json object below
        data: arrayofproductsandthereassociates,
        success: function () {
  console.log(date);

arrayofproductsandthereassociates is populated, looks like this:

var arrayofproductsandthereassociates  = JSON.stringify({"Date":date,"Item":itemName,"Sold":sold,"Void":v0id,"Comp":comp,"Price":price,"Cost":cost,"Gross":gross,"Comps":comps,"Total Tax":totaltax,"Net":net,"Gross Proft":grossprofit,"Category":category});

When Laravel gets this payload using this controller code:

           $input = Input::all();
           print_r($input);
           $itemz = json_decode($input[0]);
           $model = new DATA;
           foreach($itemz as $key => $value) 
           {
           $model->$key = $value;      
           }
           $model-save();
           return;

It errors on the json_decode($input[0]); line, saying undefined offset.

The array looks all messed up at the print_r()

Output:

Array ( [{"Date":"09-28-2016","Item":"Reuben_Hot","Sold":"1","Void":"0","Comp":"0","Price":"$2_35","Cost":"$0_00","Gross":"$2_79","Comps":"$0_00","Total_Tax":"$0_44","Net":"$2_35","Gross_Proft":"$2_35","Category":"Soups_] => [Sandwiches"}] => )

How do I solve this? My sense is that the unmatched => in the array is the reason why I have an undefined offset? But how do I fix that?

Thank you!



via Summer Developer

Laravel: how I can write my onw function with own query on my model?

Example: I wanna create my own function for laravel model like:

(original query)

SELECT
   AVG(persons_positions.points)
FROM
    positions
INNER JOIN persons_positions ON (
    positions.id = persons_positions.position_id
)
WHERE positions.country = 1
AND persons_positions.person_id = 2

(model class)

class Menedzher extends Model {
    function oh ($x) {
        return DB::table('positions')
            ->join('persons_positions', 'positions.id', '=', 'persons_positions.position_id')
            ->where('positions.country', $x) // see here
            ->where('persons_positions.person_id', '=', $this->id ) // see it!!
            ->select(DB::raw('AVG(persons_positions.hits)'));

    }
}

and to use it:

Menedzher::get(1)->oh(3)

Thanks!



via Olaf Erlandsen

SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: YES)

In my Ubuntu VM, I kept getting
SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: YES)
I have configured my database like this in my .env file
DB_HOST=45.55.88.57
DB_DATABASE=bheng-prod
DB_USERNAME=forge
DB_PASSWORD=*********
UNIX_SOCKET=/var/run/mysqld/mysqld.sock

What else I should look into to prevent this ?

I have a feeling that I have the wrong password.
How do I test my database password ? DB_PASSWORD=********* ?


via ihue

how to get laravel single locale string in blade template?

This is my message.php file which in my locale file.Code are given bellow.

return [
    'title' => 'This is Bangla Page',
];

Now i want to retrieve my string 'This is Bangla Page' . How to do that. I use blade templating and write @lang('messages.title') but it shows me Array to string conversion error.



via Md Zannatul Haque Siam

Appends Laravel collection with another collection

I trying to append an Eloquent collection with another Eloquent collection in Laravel 5.3. I tried to use merge() but it seems i'm stuck with this kind of problem:

Collection merge eating up some rows

Any ideas?



via tronic

How to fix Vue.js warning: Error when rendering component on Laravel Passport installation?

I'm new at Laravel, I tried a new fresh installation of Laravel 5.4 with Laravel Passport (as I need an OAuth2 server and API authentication package).

I did everything in the official guide (no errors) but after log in I get this:

app.js:34172 [Vue warn]: Error when rendering component <passport-authorized-clients> at /var/www/html/dev/resources/assets/js/components/passport/AuthorizedClients.vue: 

app.js:34086 TypeError: Cannot read property 'name' of undefined

So basically I can see the page with the 2 areas "OAuth Clients" and "Personal Tokens" but after some seconds it automatically generates many empty inside the first table (like the picture below).

Laravel Passport

I tried to reinstall everything 2 times same results, what's the possible issue?



via NineCattoRules

project name getting removed from the link in laravel

I have a laravel project running in my Win10 laptop using xampp,I was trying to remove the /public from the address bar but I ended up making my project unrunnable,I removed all the changes which I have done and brought it back to how it was. Now,when I run localhost/myprojectname/public it shows me this

Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

If you think this is a server error, please contact the webmaster.

Error 404

localhost
Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.6.28



via this.Believer

How to merge Laravel's Baum hierarchy trees into a single tree?

I'm using Laravel 5.1 and etrepat/baum package for implementing nested sets on my Category model.

I've a collection of categories, for each one I get their ancestor's hierarchy tree like this:

$category->getAncestorsAndSelf()->toHierarchy();

For example, let's say I have 4 categories: Category C, Category D, Category E and Category F. And each tree looks like this:

  • Category A
    • Category B
      • Category C
  • Category A
    • Category B
      • Category D
  • Category A
    • Category B
      • Category C
        • Category E
  • Category A
    • Category F

I'm trying to merge them into one tree like this:

  • Category A
    • Category B
      • Category C
        • Category E
      • Category D
    • Category F

So far I've tried the merge() function and a custom recursive function with no luck, I always end up with duplicates.



via Camilo

Using Multiple where condition and variables in laravel 5 MYSQL Query

This my query in which I want to use variables to be compared with the fields in the database table to get the price field from it.
 $price = DB::table('price')
       ->where([
    ['days_id', '=',  $days] , ['deals_id' , '=', $selected_deal]
        ])
       ->value('price');



via Abbas Ahmad

[SOLVED]how to add multiple scope to DB::table in laravel 5.4

I am new on laravel 5, I was trying to add multiples scopes like this:
$projects = DB::table('projects AS p')->select('p.project_name','c.name_country', 'p.date_project','s.name_status','p.rejected_date')                    
                    ->join('country AS c','c.id','=','p.id_country')
                    ->join('status AS s','s.id','=','p.id_status')
                    ->where('p.active','=','1');  

$projects = $this->scopeCountry($projects , $country);
$projects = $this->scopeStatus($projects , $status);  
$projects->get(); 
return view('search.ajax')->with('projects', $projects);
}
    public function scopeCountry($query, $country){
            return is_null($country) ? $query : $query->where('p.id_country','=',$country);
        }

public function scopeStatus($query, $status){
            return is_null($status) ? $query : $query->where('p.id_status','=',$status);
        }
}

It gave me this error: ErrorException in 26864233b0cd26a1055b66c2645628be451523fd.php line 4: Undefined property: Illuminate\Database\MySqlConnection::$project_name (View:/home/vagrant/Code/projects/resources/views/search/ajax.blade.php)
I noticed that this error doesn't show up if I modify it like this:
//$projects = $this->scopeStatus($status);  
//$projects->get(); 

And then I add the get() function in:
public function scopeCountry($query, $country){
                return is_null($country) ? $query->get() : $query->where('p.id_country','=',$country)->get();
            }

The reason why I don't add the queries in one scope and I use is_null($country), is because in case those variables($country, $status) were null only the main query should be executed:
$projects = DB::table('projects AS p')->select('p.project_name','c.name_country', 'p.date_project','s.name_status','p.rejected_date')                    
                        ->join('country AS c','c.id','=','p.id_country')
                        ->join('status AS s','s.id','=','p.id_status')
                        ->where('p.active','=','1'); 

And also I have to add similar scopes to another fields, maybe there is another way to do it, I am not sure. Thank you.



via Luis

[SOLVED]Laravel 5.2 Auth Scaffolding Reset Password Email Not Firing - Is it queued?

Ok so I am currently using Mandrill for email. I have assumed this is not the issue. This test route, for example fires fine.
 public function email($emailAddress){
        $data = array(
            'email'     => $emailAddress,
            'name'      => 'Test Name'
            );
        $result = Mail::queue('emails.test', $data, function ($message) use ($data){
            $message->from(Config::get('settings.contact_form_from.address'), Config::get('settings.contact_form_from.name'));
            $message->sender(Config::get('settings.contact_form_from.address'), Config::get('settings.contact_form_from.name'));
            $message->to($data['email'], $data['name']);
            $message->subject('Test email to: ' . $data['email']);
        });
        return $this->response($result);
    }

This is using the queue function. If adjusted to Mail::send() also work's fine. Thus all my queue handlers and mail env variables are working fine. (I can see both these emails in Mandrill).
So my issue is the the password reset functionality which I have installed using the Laravel 5.2 Auth Scaffolding.
So, the route etc all works fine - just no email sends.
It correctly identifies if the user does/doesn't exist (displays the correct error message).
So then I have a look through source code and got slightly lost, help is needed!
If i look in here... ...Illuminate\Foundation\Auth\ResetPasswords.php I can see this method.
public function sendResetLinkEmail(Request $request) { $this->validateSendResetLinkEmail($request);
$broker = $this->getBroker();

$response = Password::broker($broker)->sendResetLink(
    $this->getSendResetLinkEmailCredentials($request),
    $this->resetEmailBuilder()
);
switch ($response) {
    case Password::RESET_LINK_SENT:
        return $this->getSendResetLinkEmailSuccessResponse($response);
    case Password::INVALID_USER:
    default:
        return $this->getSendResetLinkEmailFailureResponse($response);
}

}
If I break at $response I am getting response that it is sent correctly. So I assume it is something to do with Password::broker section, the code here completely looses me.
Any help much appreciated!



via Matt The Ninja

Laravel: yield('content')

I created a view:
@extends('layouts.dashboard')
@section('wrapper')

<table class="table table-striped">
  <tr>
    <th>Username</th>
    <th>Event-count</th>
    <th>Is active</th>
  </tr>

And: layouts.dashboard
<div class="main-panel">
    @yield('section')
</div>
            <footer class="footer">

And now the table is shown on top and not in the div class="main". Does anyone know why?


via AppleForTheKing

Error in Relationship of tables

Im having a error when i try to get some data between 2 tables using eloquent. The error that is giving me is:
Error:
Trying to get property of non-object (View: 

This is my app information
DB:
survey:
- id;
- template_id;
- title;


templates:
- id;
- name;
- internal_name;

SurveyModel:
 public function theme(){

        return $this->hasOne(Template::class, 'template_id','id');
}


View:

@foreach($surveys->reverse() as $survey)

        <tr>
        <td></td>

</tr>
@endforeach



via Pedro

file_put_contents(..../bootstrap/cache/services.json): failed to open stream: No such file or directory


I did a fresh clone of my L5 project on my Mac OS.
Going to my site via Chrome, I kept getting this error
ErrorException in Filesystem.php line 81:
file_put_contents(/Applications/MAMP/htdocs/code/bunlong-web-app/bootstrap/cache/services.json): failed to open stream: No such file or directory

I already did :
chmod -R 777 bootstrap/ storage/ vendor/

and my file permissions look like this :
-rw-r--r--   1 bheng  staff     777 Feb 27 11:52 phpunit.xml
-rw-r--r--   1 bheng  staff      87 Feb 27 11:52 phpspec.yml
-rw-r--r--   1 bheng  staff     481 Feb 27 11:52 package.json
drwxr-xr-x   3 bheng  staff     102 Feb 27 11:52 note
-rw-r--r--   1 bheng  staff     967 Feb 27 11:52 md-bheng-readme.txt
-rw-r--r--   1 bheng  staff     503 Feb 27 11:52 gulpfile.js
drwxr-xr-x   5 bheng  staff     170 Feb 27 11:52 database
-rw-r--r--   1 bheng  staff      26 Feb 27 11:52 contributors.txt
drwxr-xr-x  13 bheng  staff     442 Feb 27 11:52 config
-rw-r--r--   1 bheng  staff  121337 Feb 27 11:52 composer.lock
-rw-r--r--   1 bheng  staff     949 Feb 27 11:52 composer.json
drwxrwxrwx   5 bheng  staff     170 Feb 27 11:52 bootstrap
-rw-r--r--   1 bheng  staff    1635 Feb 27 11:52 artisan
drwxr-xr-x  21 bheng  staff     714 Feb 27 11:52 app
-rw-r--r--   1 bheng  staff      43 Feb 27 11:52 Procfile
-rw-r--r--   1 bheng  staff       0 Feb 27 11:52 Icon?
-rw-r--r--   1 bheng  staff    5634 Feb 27 11:52 Gruntfile.js
drwxr-xr-x   4 bheng  staff     136 Feb 27 11:52 tests
drwxrwxrwx   5 bheng  staff     170 Feb 27 11:52 storage
drwxr-xr-x   4 bheng  staff     136 Feb 27 11:52 sql
-rw-r--r--   1 bheng  staff     560 Feb 27 11:52 server.php
drwxr-xr-x   5 bheng  staff     170 Feb 27 11:52 resources
-rw-r--r--   1 bheng  staff    1794 Feb 27 11:52 readme.md
-rw-r--r--   1 bheng  staff     105 Feb 27 11:52 pull.sh
drwxr-xr-x  24 bheng  staff     816 Feb 27 11:52 public
drwxrwxrwx  30 bheng  staff    1020 Feb 27 11:55 vendor

I tried
composer dump-autoload

I got
Generating autoload files

What elses I should look into ?
Is my permission set look okay ?
I just want to be able to see my site back.

I went to the file directory looking for the file that it looking for, and I didn't see it there.

Anyone know why my service.json is not get populated ?


via ihue

Mail::send laravel - How to access $message->to($variable);

I'm using the function below to send Email:
public static function send_welcome_mail($user,$code)
{
    Mail::send('auth.email.welcome',['user'=>$user,'code'=>$code], function ($message)
    {
        $message->subject('Welcome');
        $message->from('info@example.com', 'Example');
        $message->to('info@exampleReceiver.com');
    });
}

Sending Email works fine , but when i change to this (add receiver):
public static function send_welcome_mail($user,$code,$receiver)
{
    Mail::send('auth.email.welcome',['user'=>$user,'code'=>$code], function ($message)
    {
        $message->subject('Welcome');
        $message->from('info@example.com', 'Example');
        $message->to($receiver);
    });
}

I got error:
Undefined variable: receiverEmail


via skate

[SOLVED]cannot using attach() method in laravel

I have the following relations set up:
public function notes()
{
    return $this->belongsToMany(Note::class);
}


public function tags()
{
    return $this->belongsToMany(Tag::class);
}

and pivot table like this:
Schema::create('note_tag', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('note_id')->unsigned()->index();
        $table->foreign('note_id')->references('id')->on('tags')->onDelete('cascade')->onUpdate('cascade');
        $table->integer('tag_id')->unsigned()->index();
        $table->foreign('tag_id')->references('id')->on('notes')->onDelete('cascade')->onUpdate('cascade');
    });

now, i used Attach() method:
$note->tags()->attach($tagsIds);

but that is not work and get this error:
[Symfony\Component\Debug\Exception\FatalErrorException] Cannot instantiate interface phpDocumentor\Reflection\DocBlock\Tag


via narges

Dynamic Subcategories Navigation with category and subcategory slug laravel

I have a table in MySQl that contains list of all categories and subcategories. Each subcategory includes assigned parent_category_id
The page controller is as follows:
Route::get('/', 'PageController@home');
Route::get('{category}', 'PageController@category_show');
Route::get('{category}/{subcategory}', 'PageController@subcategory_show');

Now to the main part of the question, I am trying to create Top Navigation and Sidebar Navigation for subcategories. The top navigation is pretty simple and this is how I managed to accomplish this in my NavigationComposer.php
class NavigationComposer
{
    public function compose(View $view)
    {
        $view->with('categories', \App\Category::where(
            array(
            'category_display_type' => 'header',
            'category_visibility' => 1
        ))->get());
    }
}

I have tried to do the same with my subcategories in my SidebarnavComposer.php All works just fine except that I need to have the category slug in the URI when I switch to one of the categories. So far I am only able to get parent_category_id in URI. I have tried to create a join, but getting some errors.
Here is the content of my SidebarnavComposer.php
class SidebarnavComposer
{
    public function compose(View $view)
    {
        $view->with('subcategories', \App\Category::where(
            array(
            'category_display_type' => 'sidebar',
            'category_visibility' => 1
        ))->get());

    }

}

I am new to Laravel so please help me if you can.
Thanks in advance


via AlexB

[SOLVED]Design 500 error page only for production

I'm looking for a modern (Laravel 5.4) way to display custom 500 error page only for HTTP (non ajax/fetch) response. I read some threads but each response looks like a trick or is outdated. There is probably something to modify in \App\Exceptions\Handler, but I did not find the "right way".
Is there a simple way to display a specific page on fatal error (uncatched, returning 500) in Laravel 5.4?
In other words, when I have a syntax error on one of my controller, it displays "Whoops something went wrong" with some HTML and 500 error code. I would like to display something else, with the same rules as default behavior (ideally only for HTML browser, not for ajax/fetch, etc.).
EDIT: only in production environment.


from Latest question asked on Laravel tag.


via rap-2-h

Update records hierarchy

I need to update herarchies, for example one parent has points 5 then its children's point will increase by +5 and so on till the end.
I am not sure what should I user here should do this in mysql or laravel ? which is the best option and also I could like to know if anyone has any good example like this.
looking for some good Idea on this, Thanks in advance


via Roop Kumar

What is the best way to push data into mobile devise?


Hello stack community !
I work on Ionic 2.0 with Laravel.php as backend. And I have a simple question :
What is the best way to push data into mobile devise ?


via Olivier Hamon

Advertisement