mardi 30 avril 2019

Laravel Queue issue

I set all the thing related to queue jobs in laravel and its working fine. But some time when I try to send email multiple times immediately then sometimes jobs table in the database is empty that means supervisor processed jobs but I don't get an email. I don't know what's going on.

I tried to research on it but no one has a suggestion for it.

'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'retry_after' => 0,
        ],

Controller
<?php

namespace App\Jobs;

date_default_timezone_set('utc');
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mail;
use Log;

class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $emailArray;    
    public function __construct($emailArray)
    {
        $this->emailArray = $emailArray;
    }
    public function handle()
    {
        try {
            $emailArray = $this->emailArray;
            switch ($emailArray['template_name']) {
                case 'email1':
                $email = $emailArray['email'];
                Mail::send('emails.' . $emailArray['template_name'], $emailArray, function ($message) use ($email) {
                    $message->from(env('FromMail', 'myemail@gmail.com'), 'My Email');
                    $message->to($email)->subject('My Email| Forgot Password');
                });
                break;

            }
            return;
        } catch (\Exception $e){Log::info($e->getMessage());}
    }
}


Push job

try {
                $userMailArray = [
                    'template_name' => 'email1',
                    'email' => $email,
                    'temp_password' => $temporaryPwd,
                ];
                dispatch(new SendEmail($userMailArray));
            } catch (\Exception $e) {
                Session::flash('invalidMail', 'Something went wrong. Please try again.');
                return back();
            }```



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2LgkQw5
via IFTTT

Unable to redirect to a new route by Ajax call after post method in Laravel

I am doing a search operation. I am passing 3 search parameters in the form, which makes an ajax call. I am getting the response from the ajax call, but I am unable to redirect it to the new route, with the search response data. When I try to redirect, I get the full HTML Response. Unable to figure out how to redirect it to the new page with the new search results.

I am using: Laravel 5.5 with Ajax

form.blade.php

  <form id="myform">
     <input type="text" name="city" id="city">
     <input type="text" name="locality" id="locality">
     <input type="text" name="type" id="type">
     <button id="search" value="Submit"> 
  </form> 

the ajax call i am making in the form.blade.php

  <script>
    jQuery(document).ready(function(){
        jQuery('#search').click(function(e){
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        jQuery.ajax({
            url: "",
            method: 'post',
            contentType: "application/json",
            data: JSON.stringify({
                type: jQuery('#type').val(),
                city: jQuery('#city').val(),
                locality: jQuery('#locality').val()                    
            }),
            success: function(result){
                jQuery('.alert').show();
                                    jQuery('.alert').html(result.success);
                                    console.log(result);
            },error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                }
            });
        });
        });
</script>

I have defined my route in api.php

Route::post('/searchlisting', 'SearchController@searchtypes');

In my SearchController i have defined the following:

public static function searchtypes(Request $request){
    $data = array(
        'city' => $request->city,
        'type' => $request->type,
        'locality' => $request->locality
    );

    $result = SearchModel::searchtypes($data);
    return view('alllistings', ['listing' => $result]);

In my SearchModel I have defined the following:

 public static function searchtypes($inp = []){
    $result = DB::table('tbl_types')
                ->where('city', $inp['city'])
                ->where('bhk', $inp['type'])
                ->where('locality', $inp['locality'])
                ->get();
    return $result;
}

In the ajax response I get the full HTML with the desired values. But how do I redirect it to the new page with the search results.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2V6Wc5n
via IFTTT

Add Horizontal line in center of A4 size page using Laravel Dompdf

I am working on invoice management system, where I need to print 2 copy of invoice (Original and Duplicate)in single A4 page to just reuse the page.

I am using Laravel 5.6 and laravel-dompdf.

I need something like this paper center lin so that folding a page to center/half of page will make 2 copies without losing any content in print.

I am parsing Laravel blade view file. I need such a solution that it uses css only.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2H08zXl
via IFTTT

Laravel: error with embedded in html

I want to do the following in my blade.php but I get a syntax error:

      <a class="btn btn-info" role="button" href="/edit')}}">Edit Profile</a>

The error is to do with the href attribute I think, how do I correct the syntax?

Error I am getting: enter image description here



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GKOOCH
via IFTTT

Laravel get every query for a gift card in order to set the residual amount

I've a gift card Model and I want to retrieve every time it has been used to determine the residual amount. Here is my GiftCardController :

public function index()
{
    //
    $tousLesBons = BonCadeau::with(['user', 'moyendepaiement'])->orderBy('created_at', 'desc')->get();

    $changed = $tousLesBons->map(function ($value, $key) {
        $value['residualAmount'] = 0;
        return $value;
    });

    return $changed->all();
}

This works properly but instead of setting the residualAmount property to 0 which I add with mapping (not a column in my database), I want to take the gift card's base amount. So if I have a gift card of 500$, I would take those 500$ and substract every time transaction the owner made.

Therefor I need to query all database rows related to the gift card and substract them to the initial amount until it hits 0$. The model has a relation to ('App\Items') so I should be able to use it.

Thanks for reading



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2DGd5t7
via IFTTT

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_id' cannot be null

I wanted to create a post with categery_id as a dropdown in post/create form, but I'm getting a SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_id' cannot be null (SQL: insert into posts (title, body, category_id, author_id, updated_at, created_at)...

I need a little help in finding what is causing this issue and here's what I have so far...

create.blade.php

    @extends('layouts.app')
        @section('content')
         <div class="container">
         <h1>Create Post</h1>
          <div class="row post_row">

       {!! Form::open(['action' => 'PostsController@store', 'method' => 'POST', 'class' => 'form']) !!}
      <div class="col-md-8">           
         <div class'form-group'>
           
           
         </div>
      </div>

      <div class="col-md-4">
        <div class'form-group'>
           
             <select class='form-control' title="category_id">
               @foreach ($categories as $category => $value)
                <option value=""></option>
               @endforeach
            </select>
        </div>
      </div>
</div>

<div class="row post_row">
   <div class="col-md-8">
     <div class'form-group'>
       
       
     </div>
  </div>
</div>

   <div class'form-group' style="padding-top: 20px">
      
      {!! Form::close() !!}
  </div>
</div>  

@endsection

PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;
use App\Category;


class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    protected $limit = 3;

    public function create()
    {
    $posts = Post::all();
    $categories = Category::all();

    return view('posts.create')->with(['posts' => $posts, 'categories' => $categories]);
}


public function store(Request $request)
    {
        $this->validate($request, [
        'title' => 'required|max:255',
        'body' => 'required'
        ]);
        //create Post
        $post = new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->category_id = $request->input('category_id');
        $post->author_id = auth()->user()->id;
        $post->save();

    return redirect('/posts')->with('success', 'Your post created created successfully');
}

public function update(Request $request, $id)
{
        $updated = Category::findorFail($id);
        $categories = $request->all();
        $category_id = $request->get('category_id');
        $updated->fill($categories)->save();

    return redirect('/dashboard')->with('success', 'Your post created updated successfully');
}

Post.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use GrahamCampbell\Markdown\Facades\Markdown;

class Post extends Model
{
    //Table Name
protected $table = 'posts';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;

protected $fillable = [
    'title',
    'excerpt',
    'body',
    'categery_id',
    'image',

];

protected $dates = ['published_at'];


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

public function category()
{
    return $this->belongsTo(Category::class);
}

public function getImageUrlAttribute($value)
{
$imageUrl = "";

if( ! is_null($this->image))
{
    $imagePath = public_path() . "/img/" . $this->image;

    if(file_exists($imagePath)) $imageUrl = asset("img/" . $this->image);
}

return $imageUrl;

}

public function getDateAttribute()
{
    return is_null($this->published_at) ? '' : $this->published_at->diffForHumans();    
}

public function getExcerptHtmlAttribute()
{
    return $this->excerpt ? Markdown::convertToHtml(e($this->excerpt)) : NULL;
}

public function getBodyHtmlAttribute()
{
    return $this->body ? Markdown::convertToHtml(e($this->body)) : NULL;
}

public function scopeLatestFirst($query)
{
    return $query->orderBy('published_at', 'desc');
}

public function scopePublished($query)
{
    return $query->where('published_at', '<=', Carbon::now());
}

}

Category.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
protected $table = 'categories';

protected $fillable = [
    'title',
    'categery_id'
];

public function posts()
{
    return $this->hasMany(Post::class);
}

public function getRouteKeyName()
{
    return 'slug';
}
}

CreatePostsTable.php

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

class CreatePostsTable extends Migration
{
   /**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('author_id')->unsigned();
        $table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('restrict');
        $table->string('title');
        $table->string('slug')->unique();
        $table->text('excerpt');
        $table->mediumText('body');
        $table->string('image')->nullable();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('posts');
}
}

So here's what I have so far, does anyone see why I'm having this issue?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2LedSaG
via IFTTT

how to return multiple results using api controller in laravel and vuejs

I,m building a project using Laravel and Vuejs, I'm using API controllers. I want to fetch the number of users.

User controller :

public function index() { return User::where('type','!=','admin'); }

User.vue :

axios.get('api/user').then(({data})=>(this.enseignants=data.data));



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GTGQIG
via IFTTT

NotFoundHttpException on all routes

I am installing laravel existing project via vagrant, When I enter to the local url of the project, in any page I get the same error: NotFoundHttpException . Here is the screenshot of the error http://prntscr.com/nivwho

When I print something in "public/index.php" and do die after it I can see that the url is accessing to index.php file, but after that it gives this exeption. Tried to disable .htaccess file, no success the routes does not work aswell, when printing someting in top of web.php rout it is not showing any error or printed string.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2ISZG4W
via IFTTT

Laravel Passport Client Credentials Grant

I use Laravel Passport for my API authentication. I have already set up a Password Credentials Grant and it works. Now I need a Client Credentials Grant for machine-to-machine authentication.
I created a new client with php artisan passport:client --client. I tried to make a request to /oauth/token with this body (with Insomnia):

{
    "client_id":3,
    "secret":"wJWuVVydkHIQQ6gC7xvd0eEKytIFAD3pa149e6TR",
    "grant_type":"client_credentials"
}

That's the response i get from Passport:

{
  "error": "invalid_client",
  "error_description": "Client authentication failed",
  "message": "Client authentication failed"
}

Does anyone have any idea why it is an invalid client?
This is the entry in the oauth_clients table for my client, exported as json:

{
    "id":"3",
    "user_id":null,
    "name":"ClientCredentials Grant Client",
    "secret":"wJWuVVydkHIQQ6gC7xvd0eEKytIFAD3pa149e6TR",
    "redirect":"",
    "personal_access_client":"0",
    "password_client":"0",
    "revoked":"0",
    "created_at":"2019-04-30 17:06:17",
    "updated_at":"2019-04-30 17:06:17"
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GT3qRY
via IFTTT

Error "You don't have permission to access / on this server." when deploy on Heroku?

I have deployed my laravel 5.4 app on Heroku. The problem is, I am getting this error message:

Forbidden You don't have permission to access / on this server

My Procfile:

web: vendor/bin/heroku-php-apache2 public/

My composer.json

     "post-install-cmd": [
         "php artisan clear-compiled",
         "php artisan optimize",
         "chmod -R 777 public/"
     ]



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2IPQ7np
via IFTTT

Order collection by newest relationship model Laravel

I have two models Chat and ChatMessage.

Chat has many ChatMessage, i want to get all the Chat ordered by the ChatMessage created_at

So if the created_at of the ChatMessage has a date closest to today, that chat should be ordered first.

how could this be done?

I just have this

Chat::leftJoin('chat_messages', 'chats.id', '=', 'chat_messages.chat_id')
->orderBy('chat_messages.id', 'DESC');

but this does not work. i am not getting the newest row of chat_messages.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2IORh2J
via IFTTT

htaccess rewrite url to always have a default tag like this for every route: www.xyz.com/"~khane2"/

I'm trying to set up my laravel project made on a local appache server on a internal hosting service of my university.

The problem I am having is that except for the routes related to my laravel projects Authorisation/Authentication (HomeController) stuff other routes do not work as this prefix header should always be in the link for every route but the header is not added for the rest of the routes. See bolded part of this link, I need this "/~khane2/" for every page in my website.:

https://www.cs2410-web02pvm.aston.ac.uk/~khane2/home

Here is my web.php of my laravel project:

Route::get('/animal_user_change_status/{animal_id}/attach', 'Animal_usersController@attach');
Route::get('/animal_user_change_status/{animal_id}/{user_id}/detach', 'Animal_usersController@detach');
Route::get('/animal_user_change_status/{animal_id}/{user_id}/Accept', 'Animal_usersController@setAcceptToStatusColumn');
Route::get('/animal_user_change_status/{animal_id}/{user_id}/Reject', 'Animal_usersController@setRejectToStatusColumn');
Route::get('/viewuserdata', 'Animal_usersController@viewUserData');
Route::get('/viewanimalsdata', 'Animal_usersController@viewAnimalData');

Route::get('/', 'AnimalController@index'); // just incase anything redricts to '/'
Route::resource('Animal', 'AnimalController');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');

Here is my .../public_html/.htaccess from my server (I copied and pasted this code into .htaccess given by my university professor, but this is not working for all routes, I need it to work for all routes that are shown in the web.php above.):

    <IfModule mod_rewrite.c>
 <IfModule mod_negotiation.c>
 Options -MultiViews -Indexes
 </IfModule>
 Options +FollowSymLinks
 RewriteEngine On
 # Handle Authorization Header
 RewriteCond %{HTTP:Authorization} .
 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
 #Redirect Trailing Slashes If Not A Folder...
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_URI} (.+)/$
 RewriteRule ^ %1 [L,R=301]
 #Handle Front Controller...
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_URI} /(~[^/]+)(.*)
 RewriteRule ^ /%1/index.php [L]
</IfModule>

Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2Lg7Jen
via IFTTT

Laravel Associate with relationship and create if not exists

Hi I am new laravel and struggling a bit on understanding how to create relationships. I am trying to make a basic restful api in laravel and have 3 models

class Book extends Model {
   public function author()
   {
        return $this->belongsTo(Author::class);
   }

   public function categories()
   {
        return $this->belongsToMany('App\Category', 'category_book')
        ->withTimestamps();
   }

}

class Author extends Model
{
    public function books(){
        return $this->hasMany(Book::class);
    }
}

class Category extends Model
{
    public function books()
    {
        return $this->belongsToMany('App\Book', 'category_book')
           ->withTimestamps();
    }
}

Table migrations:

Schema::create('books', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('ISBN', 32);
    $table->string('title');
    $table->integer('author_id')->unsigned();
    $table->float('price')->default(0);
    $table->timestamps();
});

Schema::create('authors', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('surname');
    $table->timestamps();
});

  Schema::create('categories', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
}); 

Schema::create('category_book', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->integer('category_id')->unsigned();
    //$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    $table->integer('book_id')->unsigned();
    //$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
    $table->timestamps();
});   

books is the main table and author has a one to many relationships with books. Category has a many to many relationship with books as a book can be in more than one category.

The books table has an author_id field to link it to the author's table. There is also a pivot table called category_books that contains category_id and book_id to link books to categories.

Say I want to create a new book record and if the author exists to associate the book to that author but it if doesn't exist I want to create a new author record and then associate the book to that author?

I would also like to be able to do the same thing with categories

I have the following in my bookscontroller:

    public function store(Request $request)
    {
        $book = new book;
        $book->title = $request->title;
        $book->ISBN = $request->ISBN;
        $book->price = $request->price;
        $book->categories()->associate($request->category);
        $book->save();

        return response()->json($book, 201);
    }



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2J5GrVm
via IFTTT

How to put 2 labels and distinct tooltips from two bars

I'm trying to put two more features on this chart.

At the bottom, the graph displays the 12 months of the year with two bars for each month. One is that of the current year and the other of last year. I would like each bar is its own label to be able to display for example: April 2019 and next april 2018

And then I block on the tooltips. The still when one passes the mouse they display the information of the current year and those of the preceding year. The problem is at the level of the total where it displays the totoal of the two years.

On my side I try to display only the total of the bar where is the mouse. In summary the total for 2019 passing the mouse on the bar of 2019 and the total of 2018 passing on that of 2018.

My fiidle :

jsfiddle.net/gcr8z257/3/



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2PIi0P2
via IFTTT

Laravel query relationship based on name not id

Hi I am new laravel and struggling a bit on understanding how to query relationships. I am trying to make a basic restful api in laravel and have 3 models

class Book extends Model
{

    public function author()
    {
        return $this->belongsTo(Author::class);
    }

    public function categories()
    {
        return $this->belongsToMany('App\Category', 'category_book')
        ->withTimestamps();
    }
}

class Author extends Model
{
    public function books(){
        return $this->hasMany(Book::class);
    }
}

class Category extends Model
{
    public function books()
    {
        return $this->belongsToMany('App\Book', 'category_book')
           ->withTimestamps();
    }
}

Table migrations:

Schema::create('books', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id');
        $table->string('ISBN', 32);
        $table->string('title');
        $table->integer('author_id')->unsigned();
        $table->float('price')->default(0);
        $table->timestamps();
    });

Schema::create('authors', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('surname');
        $table->timestamps();
    });

Schema::create('categories', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    }); 

Schema::create('category_book', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('category_id')->unsigned();
        //$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->integer('book_id')->unsigned();
        //$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
        $table->timestamps();
    });   

books is the main table and author has a one to many relationship with books. Category has a many to many relationship with books as a book can be in more than one category.

The books table has an author_id field to link it to the authors table. There is also a pivot table called category_books that contains category_id and book_id to link books to categories

But how do I query books so that it returns only books based on the authors name ?

I would also like to do the same thing based on the category name?

I my books controller i have the following but not sure how to do it correctly

public function index(request $request, Author $author, Category $category)
{

    $author = $request->author;

    $books = Book::find()->author()->where('name', $author);

    $books = Book::with(['categories'])->where('name', $category);

    return response()->json($books, 200);
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2DF2Rcv
via IFTTT

Run Laravel queue on production


Could you please share your best solution for run Laravel queue on production server?

For now I see next solution:

  1. First start queue:
php artisan queue:work >> /var/log/queue.log &

  1. Add to crontab:
10 2 * * * php artisan queue:restart
11 2 * * * php artisan queue:work >> /var/log/queue.log &

  1. In case of project update on server:
php artisan down
php artisan queue:restart
#do update
php artisan queue:work >> /var/log/queue.log &
php artisan up

But I'm worrying about high load case. What if some job will be stucked?
Maybe you have better solution?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2WaqiBw
via IFTTT

Laravel dont apresent uploaded images (Shared Host)

I have a shared host, I only have access via Cpanel,

But I have a small problem, as images that upload do not appear,

Does anyone know how to solve ??

enter image description here

Code where I save the image

$request->picture->storeAs('public/upload/authors', $filename);

Code to see image

<img src="" width="75" height="75">

Does anyone know what can it be??



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2DFbZNY
via IFTTT

how implement multiple theme in laravel

i devolop a laravel project in which I want to support multiple themes. Each theme will have different color combinations. i install teeplus create two theme how i switch from one theme to other if i press only one button

see picture in sidebar as shown two theme created

when i use this function it give error Theme::set('theme1');

this function i made for two different url and for two diff theme

public function getIndex()
{
    Theme::uses('default');

    $data['info'] = 'Hello World';

    return Theme::view('index', $data);
}

public function theme()
{
    Theme::uses('theme1');



    return Theme::view('index');
}

i want when i press a button it will change only colour combination not content



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2VFj6QI
via IFTTT

Duplicate the categories of product

I need to copy the categories pivot for product id 15 and apply to another product. Is there any shorthand to do the copy paste instead of getting the array and attach loop throgh?

$product = App\Product::find(15);

$product->categories()->attach([1, 5]);



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2WaFcI8
via IFTTT

Laravel 5.0 Collection contains() not working as expected?

I have a collection of my relationship. 1 Mailgroup has many ExternalClients.

When I dd this collection like this:

dd($mailgroup->externalClients);

I get this result:

Collection {#304 ▼
  #items: array:1 [▼
    0 => ExternalClient {#303 ▼
      #table: "external_clients"
      +timestamps: false
      #casts: array:1 [▶]
      #fillable: array:7 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      #attributes: array:8 [▼
        "id" => 1
        "firstname" => "Ganesan "
        "lastname" => "Pandaram"
        "email" => "mailtoganesh.p@gmail.com"
        "active" => 1
        "lang" => "nl"
        "company" => "ypto"
        "site_id" => 4
      ]
      #original: array:10 [▶]
      #relations: array:1 [▶]
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
    }
  ]
}

Now I want I try the $collection->contains() function like this I get nothing.

if ($mailgroup->externalClients->contains('mailtoganesh.p@gmail.com')) {
    echo 'yes';
}

I am expecting to see 'yes' because we can see that the "mailtoganesh.p@gmail.com" is in the collection.

I've also tried this:

if ($mailgroup->externalClients->contains('email', 'mailtoganesh.p@gmail.com')) {
    echo 'yes';
}

This gives me this error:

Object of class Closure could not be converted to int



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2DDzasc
via IFTTT

Problem with Eloquent query filtering by value 0 in tinyint field

I have a user filter that filters by name, email and user type (admin or regular user)

I´m using eloquent query builder, and the field in the database is tinyint with values 0 for regular user and 1 for admin.

When trying to filter by regular user (0) I get all the users including the admins. And when I filter by admin I get the admins.

So somehow filtering by 0 returns all usertypes.

This is the query I´m using:

`

 * Scope a query to requested filters.
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeFilter($query)
{

    if(request('usertype')){

        $query->where('admin', request('usertype'));

    }

    return $query->orderBy('name', 'ASC');
}`

Can someone help?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2vvkSW9
via IFTTT

How to enable oci8 for PHP7.2 on Ubuntu18.10

I am following the this link to enable the oci8 extension for me but I still don't see the oci8 extension enabled in my phpinfo. Any help or step by step guide would be appreciated. I am using PHP7.2 as a service, apache2.4, on Ubuntu18.10 with oracle 11gR2 installed on my local as well



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2XUXVrw
via IFTTT

relational Database delete in laravel

I am setting up a two database table, sale item and sale. When an admin make an inventory multiple sale item can added. After complete my sale inventory, i want to delete sale but i do not want to delete sale item table. My Sale Item migration table is:

public function up()
 {
    Schema::create('sales_items', function (Blueprint $table) {
        $table->increments('id');
        $table->string('product_name');
        $table->string('product_price');
        $table->string('product_quantity');
        $table->string('product_discount');
        $table->string('total_price');
        $table->integer('status');
        $table->integer('sale_id')->unsigned();
        $table->foreign('sale_id')->references('id')->on('sales')- >onDelete('cascade');
        $table->timestamps();
    });
}

Sale migration table is:

public function up()
{
    Schema::create('sales', function (Blueprint $table) {
        $table->increments('id');
        $table->string('sale_status');
        $table->string('total_price');
        $table->string('due');
        $table->timestamps();
    });
}

SaleItem Model :

public function sales(){
    return $this->hasOne(Sale::class, 'id', 'sale_id');
}

Sale Model:

public function saleitems(){
    return $this->hasMany(SalesItem::class, 'sale_id', 'id');
}

Now, How can i delete Sale table without delete sale item table?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2J5fr8j
via IFTTT

Pivot table return null using laravel 5.7.*

I have two models named: League ans User

There's a pivot table named: league_user contains this structure:

id
user_id
league_id
joined_at
rank
payment_id
created_at
updated_at

This is my Models:

class League extends Model
{
    protected $fillable = [
        'name', 'capacity', 'is_open', 'started_at', 'finished_at', 'is_free', 'price', 'level', 'user_id', 'closed_by', 'edited_by'
    ];

    protected $hidden = [];


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


    /*
     * Editor Relationship
     */
    public function editor()
    {
        return $this->belongsTo(User::class, 'edited_by');
    }

    /*
     * All users Relationship
     */
    public function all_users()
    {
        return $this->belongsToMany(User::class)->withTimestamps()->withPivot('rank', 'joined_at');
    }
}

And User Model:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'family', 'email', 'mobile', 'password', 'username', 'team', 'email_verified_at', 'mobile_verified_at', 'role_id'
        ];

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


    /*
     * Roles ralationship
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    /*
     * Question Relationship
     */
    public function questions()
    {
        return $this->hasMany(Question::class);
    }

    /*
     * League Relationship
     */
    public function leagues()
    {
        return $this->hasMany(League::class);
    }


    /*
     * Setting Relationship
     */
    public function setting()
    {
        return $this->hasOne(UserSetting::class);
    }


    /*
     * All Leagues that User Joined
     */
    public function all_leagues()
    {
        return $this->belongsToMany(League::class)->withTimestamps()->withPivot('rank', 'joined_at');
    }

}

Now when I want to access to the rank or joined_at in my pivot table, it seems something is wrong or at least I'm doing that in a wrong manner.

I tried this:

foreach ( $leagues as $league )
{
    $pivot[] = $league->pivot;
}

dd($pivot);
}

to check my pivot behavior, and I did check $league->pivot->rank or $league->pivot->joined_at either, but pivot table seems to be null!

Can any one tell me what's wrong in my code?

I saw these links:

laraveldaily

laracast

laravel documentation

and...



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2ISwUl9
via IFTTT

Filter in laravel base on multiple select languages

On my table one column is language and data stored in [English,Hindi, French] this format and in search time data come same format so how to filter data



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2IO9RYN
via IFTTT

Getting a value from a relationship within a relationship in Laravel 5.8

So I have a approved_quote relationship on my jobs Model.

public function approved_quote()
{
    return $this->hasOne(JobQuote::class, 'job_id')->whereNotNull('approved_at');
}

I want to pull back the products that have been quoted. I have tried a couple of methods however both have unexpected results.

Attempt 1

public function quoted_job_products()
{
    return $this->hasMany(JobProduct::class, 'job_id')->where('job_quote_id', $this->approved_quote()->first()->id ?? 0);
}

However $this->approved_quote->get(); pulls back 14 records that are not really relevant (or right) and so ->first() just pulls back the first of that which is wrong.

Attempt 2

public function quoted_job_products()
{
    return $this->hasMany(JobProduct::class, 'job_id')->where('job_quote_id', $this->approved_quote->id ?? 0);
}

$this->approved_quote returns null and so it does not work.

Any suggestions as to how this can be achieved? (Preferably without having a approved_quote_id on jobs however I will if I need to).



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2J2XFm5
via IFTTT

Limit sending email Laravel in once schedule task

kindly need your help. I have problem with limit email exchange from SMTP. I have counting table with specific column. total is 201. that total will send email automatic with schedule task on the server.

Counting TOTAL
enter image description here

can I send email per batch using laravel as much as 201 email in once send email ?

cronEmail

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:reminder';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Command description';

/**
 * Create a new command instance.
 *
 * @return void
 */
public function __construct()
{
    parent::__construct();
}

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->updateMailConfig();
    $check = DB::table('a_kpi')->join('d_mem','k_created_by','m_id')
    ->leftjoin('a_kpid','kd_kpi_id','k_id')
    ->where('k_status_id',1)
    ->where(function($query){
        $query->where('kd_status_id','=','In Progress')
                ->orwhere('kd_status_id','=',null)
                ->orwhere('kd_status_id','=')
                ->orwhere('kd_status_id','=','null')
                ->orwhere('kd_status_id','=',"null");
    })
    ->get();

    $dt = date("Y-m-d");
    $dtdt = date( "Y-m-d", strtotime( "$dt +10 day" ) );
    for ($i=0; $i <count($check); $i++) { 
        if ($check[$i]->kd_duedate == $dtdt) {
           $mail = $check[$i]->m_email;
            Mail::send('mail.tes', 
                ['pesan'         => 'KPI INFORMATION',
                 'k_label'       => $check[$i]->k_label,
                 'kd_tacticalstep'  => $check[$i]->kd_tacticalstep,
                 'kd_duedate'     =>  $check[$i]->kd_duedate], 
            function ($message) use ($mail)
            {
                $message->subject('REMINDER');
                $message->to($mail);
            });


            $data = DB::table('d_log_reminder')
                                    ->insert([
                                    'dlr_id'=>$check[$i]->k_id,
                                    'dlr_kpi_id'=>$check[$i]->k_id,
                                    'dlr_kpid_id'=>$check[$i]->kd_id,
                                    'dlr_tacticalstep'=>$check[$i]->kd_tacticalstep,
                                    'dlr_label'=>$check[$i]->k_label,
                                    'dlr_duedate'=>$check[$i]->kd_duedate,
                                    'dlr_created_by'=>$check[$i]->k_created_by,
                                    'dlr_send_to'=>$mail
                                    ]);


        }
    }


    // $check = DB::table('d_mem')->where('m_username','admin')->update(['m_code'=>'cor'.date('d-m-y h:i:s')]);

}

}

Kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use App\Helper\ConfigUpdater;
use Mail;
use DB;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
    use ConfigUpdater;

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        'App\Console\Commands\cronEmail'
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {


            $schedule->command('email:reminder')
            ->everyMinute();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2PEad4s
via IFTTT

Is there a way to get SQLServer Triggers to work with Eloquent queries?

I am developing an application using Laravel 5.5 and SQLServer. I was asked to create a 'History' table, in which we keep track of UPDATE actions. For example, if we update the description of a ticket, we insert the id, the field, the previous value and the new value of that field.

Usually, this is done with Triggers in the Database, so I have set up an after_update trigger.

Now, my trigger works, but not when the queries are written with Eloquent. If I use the PDO object of the same connection used by my Models, the triggers work. If I write a query in the Database interface, using the same connection, they work. But if I write the same query with Eloquent, the field is updated, but the triggers do not fire.

I am aware that Observers exist to act like triggers, and I did set them up to do pretty much the same thing. But, I don't understand why the triggers do not work, and i wonder if it is a normal behavior or if my set up is faulty in some way.

My connection in the database.php file looks like this (with default values i removed here) :

'uti' => [
            'driver'   => 'sqlsrv',
            'host'     => env('DB_HOST'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'prefix'   => '',
            'charset'   => 'iso-8859-1',
            'characterset' => 'iso-8859-1',
            'collation' => 'French_CI_AS',
        ],

The code with which the trigger works :

use Illuminate\Support\Facades\DB;

$oPdo = DB::connection('uti')->getPdo();
$sQuery = $oPdo->prepare("
            UPDATE TICKET SET
            T_DESC = :sDesc
            WHERE T_CODE = :iCode");
$sQuery->execute([':sDesc' => $sDesc, ':iCode' => $code]);

The code with which it does not work :

$oTicket = Ticket::find($code);
        $oTicket->T_DESC = $sDesc;
        $oTicket->save();

The trigger is something like this (with more 'IF UPDATE()' for each field of the table TICKET):

USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[after_update_ticket]
ON [dbo].[TICKET] 
AFTER UPDATE
AS
BEGIN -- begin trigger
SET NOCOUNT ON

IF EXISTS (SELECT * FROM INSERTED) And EXISTS(SELECT * FROM DELETED)
-- Is an update --
BEGIN -- begin if update
    DECLARE @user int = 1;
        IF NOT UPDATE (MODIFICATION_DATE) AND NOT UPDATE (MODIFICATION_USER)
            BEGIN -- begin if not update
-- If database connection user is letter + number, user id = number
            IF (ISNUMERIC(SUBSTRING(USER_NAME(USER_ID (CURRENT_USER)),2, LEN(USER_NAME(USER_ID (CURRENT_USER)))))=1)
                BEGIN
                    SET @user = SUBSTRING(USER_NAME(USER_ID (CURRENT_USER)),2, LEN(USER_NAME(USER_ID (CURRENT_USER))));
                END

            -- Update MODIFICATION date and user --

                UPDATE [TICKET] SET 
                MODIFICATION_DATE = CURRENT_TIMESTAMP, 
                MODIFICATION_USER = @user
                WHERE CODE = (SELECT T_CODE FROM inserted)


            -- History trigger --
            IF UPDATE(T_DESC)
                BEGIN
                INSERT INTO HISTORIQUE 
                (H_DATE,H_TABLE,H_FIELD,H_BEFORE,H_AFTER,H_CODE,CREATION_GUT,CREATION_DATE) 
                VALUES 
                (CURRENT_TIMESTAMP,'TICKET','T_DESC',(SELECT T_DESC FROM deleted),(SELECT T_DESC FROM inserted),(SELECT T_CODE FROM inserted),@user,CURRENT_TIMESTAMP)
                END
END -- end if no update

END -- end if update

END -- end trigger


I have tried researching triggers, laravel and eloquent, but looking at the docs and several stackoverflow questions did not provide me with information about the expected behavior of Triggers with Eloquent. I found that some people created them manually with migrations, so I am supposing they are supposed to work, but I could not find information to help me.

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GTRRdf
via IFTTT

Jquery not working with file input for preview

I am using following code where image preview is required before uploading

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<div class="form-group has-feedback row ">
  {!! Form::label('photo_lbl', trans('destinations.photoLabelTitle'), array('class' => 'col-md-3 control-label')); !!}
  <div class="col-md-9">
    <div class="input-group">
      {!! Form::file('photo[]', null, array('id' => 'photo_title', 'class' => 'form-control')) !!}      
      <img src="" id="photo_img" width="200px" />
    </div>
    @if ($errors->has('photo'))
      <span class="help-block">
        <strong></strong>
      </span>
    @endif
  </div>
</div>

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#photo_img').attr('src', e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
  }
}

$(document).ready(function() {
  $("#photo_title").change(function() {
    readURL(this);
  });
});



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2ZGHDnX
via IFTTT

INSERT new row or DELETE old row IF it already exists using laravel

I am assigning multiple skills to an employee using checkboxes. when a user checks the checkbox a new record is inserted into pivot table. if a user unchecks the checkbox a record is deleted.

Now i am wondering if there is any function for insert or delete like there exists for new insert or update which is updateOrCreate to update an existing record or create a new record if none exists.

I can do it the hard way. but just want to know if there is any function for this like updateOrCreate.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GKWJQF
via IFTTT

Laravel 5.7 php getimageinfo 'failed to open stream'

I am attempting to get the dimensions of an image file that IS successfully uploading to my public/images folder which IS correctly symlinked via Laravel to the storage/public folder. I am using PHP's getimageinfo function.

To store the file, I have used the built in ->store('pathtodirectory', 'public') to save the file to the server, which is working. It correctly returns the path/filename associated with the image, and properly saves the file which I can confirm and view.

However! When I attempt to use the getimageinfo function it tells me 'failed to open stream'. I have attempted to use the Storage::url, and the storage_path functions to grab a path to the file and pass that into getimageinfo. I have attempted to use the Laravel asset function as well. Nothing is working.

What am I missing?

Code:

    $photo = $request->file('image');
    $imageFilePath = $photo->store('images', 'public');
    $imageDimensions = getImageSize(Storage::url($imageFilePath));<--Fails here


My config/filesystems.php:

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
    ],

],



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2PDYlQ1
via IFTTT

lundi 29 avril 2019

How to extend or make custom PasswordBroker sendResetLink() method in Laravel 5.8?

Currently the logic behind Resetting Password is that user must provide valid/registered e-mail to receive password recovery e-mail.

In my case I don't want to validate if the e-mail is registered or not due to security concerns and I want to just do the check in back-end and tell user that "If he has provided registered e-mail, he should get recovery e-mail shortly".

What I've done to achieve this is edited in vendor\laravel\framework\src\Illuminate\Auth\Passwords\PasswordBroker.php sendResetLink() method from this:

 /**
     * Send a password reset link to a user.
     *
     * @param  array  $credentials
     * @return string
     */
    public function sendResetLink(array $credentials)
    {
        // First we will check to see if we found a user at the given credentials and
        // if we did not we will redirect back to this current URI with a piece of
        // "flash" data in the session to indicate to the developers the errors.
        $user = $this->getUser($credentials);

        if (is_null($user)) {
            return static::INVALID_USER;
        }

        // Once we have the reset token, we are ready to send the message out to this
        // user with a link to reset their password. We will then redirect back to
        // the current URI having nothing set in the session to indicate errors.
        $user->sendPasswordResetNotification(
            $this->tokens->create($user)
        );

        return static::RESET_LINK_SENT;
    }

to this:

 /**
     * Send a password reset link to a user.
     *
     * @param  array  $credentials
     * @return string
     */
    public function sendResetLink(array $credentials)
    {
        // First we will check to see if we found a user at the given credentials and
        // if we did not we will redirect back to this current URI with a piece of
        // "flash" data in the session to indicate to the developers the errors.
        $user = $this->getUser($credentials);

//        if (is_null($user)) {
//            return static::INVALID_USER;
//        }

        // Once we have the reset token, we are ready to send the message out to this
        // user with a link to reset their password. We will then redirect back to
        // the current URI having nothing set in the session to indicate errors.
        if(!is_null($user)) {
            $user->sendPasswordResetNotification(
                $this->tokens->create($user)
            );
        }

        return static::RESET_LINK_SENT;
    }

This hard-coded option is not the best solution because it will disappear after update.. so I would like to know how can I extend or implement this change within the project scope within App folder to preserve this change at all times?

P.S. I've tried solution mentioned here: Laravel 5.3 Password Broker Customization but it didn't work.. also directory tree differs and I couldn't understand where to put new PasswordBroker.php file.

Thanks in advance!



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2UQW5Gp
via IFTTT

View Composer not working in my Laravel App

I am trying to share variables on multiple views so i tried the view composer but it is not working as its not passing variables and is there any way to debug it

ComposerServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            'layouts.admin.dashboard',
            'App\Http\ViewComposers\StatComposer'
        );
    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

So now here will be the Composer File

StatComposer.php

   <?php

namespace App\Http\ViewComposers;

use Analytics;
use Spatie\Analytics\Period;
use App\Libraries\GoogleAnalytics;
use Illuminate\Http\Request;
use Illuminate\View\View;

class StatComposer
{
    /**
     * Create a movie composer.
     *
     * @return void
     */
    public function __construct()
    {
        $result = GoogleAnalytics::topCountries();
        $country = $result->pluck('country');
        $country_sessions = $result->pluck('sessions');

        $topBrowsers = GoogleAnalytics::topBrowsers();
        $browser = $topBrowsers->pluck('browser');
        $browser_sessions = $topBrowsers->pluck('sessions');

        $totalPageViews = GoogleAnalytics::fetchVisitorsAndPageViews();
        $date = $totalPageViews->pluck('date');
        $visitors = $totalPageViews->pluck('visitors');
        $pageViews = $totalPageViews->pluck('pageViews');
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('country', 'country_sessions', 'browser', 'browser_sessions','date','visitors','pageViews');
    }
}

So I am unable to find way to debug it as the variables are not passing to the view i am trying to pass them to and the view is giving error of undefined variable.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2DFisIZ
via IFTTT

Laravel Query builder - multiple sum() issue

Hei there, I'm new in laravel and I have some issues with laravel query builder. The query I would like to build is this one:

Select nofaktur, date, diskon, namacust, SUM(subtotal)+SUM(diskon)) as subtot, SUM(diskon) as totaldiskon, total From crLap GROUP BY nofaktur Order By date, nofaktur.

i've tried like this

$penjualan = DB::table('report_penjualan') ->select('nofaktur', DB::raw('(SUM(subtotal)+SUM(diskon)) as subtot'), DB::raw('SUM(diskon) as totaldiskon')) ->groupBy('nofaktur') ->get()->toArray();

but the field 'date', 'diskon' etc can't be shown..



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2J4RDBB
via IFTTT

Is there a way to go back from production to testing with laravel 5.6

Some guy made a site with laravel 5.6 and we at a different place need to change just some tags and the CSS, I have a git of the site but vendor .env and many files are missing because it was already in production mode, how can I open the site in my computer to adjust the style sheets I have no database backup and also installed laravel 5.6 and try to paste de missing files but there are still many errors.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2ZLFVBQ
via IFTTT

Online email verification with laravel

I used mailtrap to run email verification locally, and everything seemed working fine. Once I pushed it to heroku, mailtrap stopped working to send the emails. I've tried a bunch of things including the sendgrid addon, but my account was suspended as I logged in to sendgrid.

Someone is supposed to register, and then get an email to verify their email...It is for a voting platform and I need maximum security. Please help. Urgent!



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2PAQ9Ad
via IFTTT

Laravel 5.8 newing up eloquent model and calling accessor in one line?

I have a contact_info_scopes table and one of the scopes is 'Default', which is likely to be the most common scope called, so I'm creating an accessor

public function getDefaultScopeIdAttribute()
{
    return $this::where('contact_info_scope', 'Default')
        ->first()
        ->contact_info_scope_uuid;
}

to get the defaultScopeId and wondering how I can new up the ContactInfoScope model and access that in one line. I know I can new it up:

$contactInfoScope = new ContactInfoScope();

and then access it:

$contactInfoScope->defaultScopeId;

but I would like to do this in one line without having to store the class in a variable. Open to any other creative ways of tackling this as well! Thanks :)



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2L70KEi
via IFTTT

(Laravel) Failed to open stream: Permission denied

I am trying to use composer update but I get this error

[ErrorException]                                                                                                                            
 copy(/home/user/.composer/cache/files/nexmo/client/9a77c8d9a60db16a277ace89703c6d841e17b77a.zip): failed to open stream: Permission denied



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GFMrkI
via IFTTT

How can I connect to Laravel broadcasting from c# desktop app?

I have laravel chat application working through laravel broadcasting on laravel-echo-server. On front end I subscribe to channels and listen events using laravel-echo npm package, but how can I subscribe to channels in desktop app written on c# ?

I expect to have something like this written on c#:

Echo.private('SomeChannel')
    .listen('SomeEvent', (response) => {});



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2WePFSS
via IFTTT

Api access over virtual host and port?

I installed laravel passport and access my api over http://127.0.0.1:8000/api, that works. But I also have my valet virutalhost like https://myapp.test, I would wish to access now the api over https://myapp.test:8000/api, is that possible? Will I have also api directly online on my domain?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GRMFqj
via IFTTT

Making PHP variable specific on jQuery each function

So I am trying to validate items in my cart, by hiding the add button whenever a user's item quantity is more than the stock, the code works fine whenever there is one item in it, however when there is multiple items, my stock variable only gets the last item's stock in the cart, not all of them

This is my code below

$('.quantity-val').each(function() {
                var initialQuantity = parseInt($(this).text());
                if (initialQuantity === 0) {
                    $(this).siblings('.fa-minus-circle').hide();
                }

                var quantity = '<?php echo $details['stock'] ?>';

                console.log(initialQuantity);
                console.log(quantity);

                if (initialQuantity == quantity) {
                    $(this).siblings('.fa-plus-circle').hide();
                }

            });

I believe I would need to make the quantity variable specific but not sure how to..

Any help would be greatly appreciated!



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2XToBZz
via IFTTT

Custom Guard Authentication Exception

I created a custom guard (admin) in my application, and everything looks good following this tutorial online (https://pusher.com/tutorials/multiple-authentication-guards-laravel). The only problem is when i try to access a view that is protected by the admin guard, instead of giving me a exception NotAuthenticate, is giving me a "InvalidArgumentException Route [login] not defined.".

My Dashboard controller custom guard is:

 public function __construct()
    {
        $this->middleware('auth:admin');
    }

But the strange thing that i cant understand whats going on is that when i add in my web.php routes the "Auth::routes();", it works fine, the Exception NotAuthenticate gets fired.

Is there a reason why my custom only works has expected with i add the Auth::routes() ?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2VxJThP
via IFTTT

How To format date in laravel 5.8 From "Thu Apr 11 2019 00:00:00 GMT+0200" to Mysql format?

I'm working on the backend for an App for school and I got a problem converting a date that I get from a request like " Thu Apr 11 2019 00:00:00 GMT+0200" to MySql format (timestamp)


public function getAll(Request $request){
        $start = $request->input('start');
        $end = $request->input('end');

        // we receive some thing like:
        // Thu Apr 11 2019 00:00:00 GMT+0200 (Central European Summer Time)
        $sales = Sale::with('SaleLine.lens','SaleLine.cadre','cli_sale')
                    ->whereBetween('created_a', [$start, $end])
                    ->orderBy('id', 'desc')->get();

        for ($i=0; $i < count($sales); $i++) {
            $sales[$i]['client_name'] = $sales[$i]['cli_sale']['first_name'] . " " . $sales[$i]['cli_sale']['last_name'];
        }
        return response()->success(['sales'=>$sales]);
    }



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2PB7LMr
via IFTTT

How to Fix Undefined Variable id error in laravel 5.7

M working on a solution where by i need to pass data from controller to view, Based on the id.

I've tested each variable one by one for see if there is actual data contained in those variables.

one-by-one produces all the values required and as soon as i comment out the var_dumps(). Throws an Undefined index error.

Please See code below:

View

<td>
   <a href="view-campaign/" class="btn btn-success mb-2"
      data-toggle="tooltip" title="view campaign">                            
        <i class="fa fa-eye"></i>
   </a>
</td>

Controller

public function viewCampaign($id){

        //return var_dump($id);

        $img = null;

        //firebase configs and send to firebase
        $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/serviceKey.json');
        $firebase = (new Factory)
            ->withServiceAccount($serviceAccount)
            ->withDatabaseUri('https://projectName.firebaseio.com/')
            ->create();

            $database = $firebase->getDatabase();

            $ref = $database->getReference('CampaignCollection')->getValue();

            foreach($ref as $key){
                $item = $key['id'];
                //return var_dump($item); 
                $poster = $key['Poster'];
                //return var_dump($poster); 
                if($item = $id){ 

                    //return '1';
                    $img = $poster; 
                    //return var_dump($poster);
                }else{
                    return '0';
                }
             }
        return view('view-campaign')->with('img',$img);
    }

Route

Route::get('view-campaign/{id}','CampaignController@viewCampaign');

View::Results

@extends('layouts.layout')

@section('content')
<div class="col-md-12">
        <div class="col-md-12 panel">
            <div class="col-md-12 panel-heading">
                <h4>View Campaign:</h4>
            </div>
            <div id="imgContainer" class="col-md-12 panel-body">
               <a href="/listCampaign" class="btn btn-danger mb-2" style="margin-bottom: 15px"><i class="fa fa-arrow-circle-left"></i></a>
               @if(isset($img))
                  <div  align="center">
                    <img src="" />
                  </div>
                @else
                  no data 
                @endif

            </div>    
        </div>
</div>
@endsection

Goal is to get the base64 code to pass to the view.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2UZI8KW
via IFTTT

access data from database to compare with current date to calculate total days

I have tried to access date stored in my db table and compare it with current date so that i can get the number of days but it shows this error

DateTime::__construct(): Failed to parse time string ([{"quit_date":null},{"quit_date":null}]) at position 0 ([): Unexpected character

This is the code that use in my controller

        $quit_date = Information::select('quit_date')
                ->where('user_id','=',\Auth::user()->id)
                ->get();
        $date = new Carbon($quit_date);
        $now = Carbon::now();
        $day = $date->diffInDays($now);

but if I set the $quit_date manually with the date for example "2019-04-25 00:00:00.000000", the code works fine and show the day different between the date, but when I use the Information::select to read the date from database, it shows error.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2DzuhQH
via IFTTT

Type error: Argument 2 passed to Illuminate\\Auth\\SessionGuard::__construct()

when i run this php artisan auth:clear-reset command terminal shows the error

Type error: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must be an instance of Illuminate\Contracts\Auth\UserProvider, null given, called in /var/www/html/coir/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 123", "exception": "Symfony\



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2La7aCy
via IFTTT

laravel errno: 150 "Foreign key constraint is incorrectly formed

I user below tutorial for laravel categories :

Laravel categories with dynamic deep paths

I use below code same tutorial for migration :

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->integer('parent_id')->unsigned()->default(0);
            $table->timestamps();
        });

        Schema::table('categories', function (Blueprint $table) {
            $table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        });

    }


but I have below error :

SQLSTATE[HY000]: General error: 1005 Can't create table 'xxx'.'#sql-453_147' (errno: 150 "Foreign key constraint is incorrectly formed")

(SQL: alter table 'categories' add constraint 'categories_parent_id_foreign' foreign key ('parent_id') references 'categories' ('id') on delete cascade on update cascade)

Thanks for help



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GQbToR
via IFTTT

How to get AVG value by pivot fields

I have some problem, I don't understand how to count AVG value when get all value from model. I have 2 model's. First it's AdminProduct - hold base info about product. Second model it's - PartnerOffer - hold partners offers for AdminProduct. And i have pivot table partner_offer_admin_product - hold 2 foreign keys for table & field price.

AdminProduct.php

public function partnerOffers()
{
   return $this->belongsToMany(PartnerOffer::class, 'partner_offer_admin_product')->withPivot('price);
}

PartnerOffer.php

public function adminProducts()
{
  return $this->belongsToMany(AdminProduct::class, 'partner_offer_admin_product')->withPivot('price);
}

Migration partner_offer_admin_product.php

Schema::create('partner_offer_admin_product', function (Blueprint $table) {
            $table->unsignedBigInteger('admin_product_id');
            $table->unsignedBigInteger('partner_offer_id');

            $table->unsignedDecimal('price', 10, 2);

            $table->foreign('admin_product_id')->references('id')->on('admin_products')->onDelete('cascade');
            $table->foreign('partner_offer_id')->references('id')->on('partner_offers')->onDelete('cascade');
        });

AdminProductRepository.php

public function getAll()
{
$products = AdminProduct::all();
// How to count avg value via pivot table field `price`
}

// How count Avg by id AdminProduct best. Below my solution.
public function getOffers($id)
    {
        $avg = DB::select('select avg(`price`) as value from `partner_offer_admin_product` where `admin_product_id` ='.$id);
        // dd ($avg);

        $collection = collect([
            'item' => [
                'product' => AdminProduct::with('partnerOffers')->find($id),
                'avg_price' => $avg
            ]
        ]);

        return $collection;
        // return $data;
    }


I expect the output object holds list partner offers with AVG all value price for every AdminProduct's



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2Lb4LYu
via IFTTT

dimanche 28 avril 2019

Result of adding two numbers in Javascript is wrong on apache but not with artisan server

I've found a weird behavior of a site that I'm developing. It is being developed using Laravel 5.8 and uses the React preset to build all the front end. This project has a section of stats, and in some of them you need to show a total field. When I use the php artisan serve to run my project, and access the stats, the results are displayed and calculated correctly. The problem comes when I deploy this site on Apache using AMPPS. When I do this, the total is calculated as a string, so for example, if I have a sum of 1+0, instead of get a 1, I'm getting a 10. It is concatenating the integers as strings.

This is the result when I'm using the php artisan serve This is the result when I'm using the <code>php artisan serve</code>

And this one when I use apache: And this one when I use apache

Why this behaviour only happens when I'm using apache as server?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2J1vS5p
via IFTTT

Getting User::create() not found in Laravel 5.5

When I try to register a user, I am getting an error:

Call to undefined method App\Models\User::create()

here is my User model:

<?php

namespace App\Models;

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

class User
{
use Notifiable;

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

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

protected $table = 'users';

}

I have used the User model that is shipped with Laravel 5.5, but just moved it to the Models folder. I updated the config/auth file to point to App\Models\User. I have ran php artisan optimize and composer dump-autoload several times, to no avail.

Here is my Register Controller:

<?php
namespace App\Http\Controllers\Auth;

use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller {

public $titles = [];

public $title = 'Registration';

use RegistersUsers;

/**
 * Where to redirect users after registration.
 *
 * @var string
 */
protected $redirectTo = '/home';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest');
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    return User::create([
        'first_name' => $data['first_name'],
        'last_name' => $data['last_name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}

public function showRegistrationForm() {
    return view('auth.register')
      ->with('env', $this->env)
      ->with('titles', $this->titles)
      ->with('title', $this->title);
}
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2ZGURkE
via IFTTT

Laravel Form posted html values getting encoded

I am using Laravel 5.6 and have created a basic form. One of my fields which is a textarea, expects some html code input. For example, I expect the user to enter

<img alt="" src="{club_logo_url}" style="float:right;width:100px;padding-right:10px;" />

where {club_logo_url} is a place holder which I look for in the backend.

I use Input::get('ticket_template') to get the posted value in the back end and this is what I get

<img alt="" src="%7Bclub_logo_url%7D" style="float:right;width:100px;padding-right:10px;" />

So how do I get the exact value as posted by the user without embedding the {} characters? thanks



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GTQ7Q7
via IFTTT

I want to pass my Foreign Key to my database and not have it null

I'm creating a web application that mimics a simple hotel booking system while also linking to a database. I have tables set up and the correct primary/foreign keys. When doing a dd to make sure I collected the data, the id keeps showing up as null, which I can't have.

I do have a foreign key set up in my reservations table to make sure they're linked when working with both of them since the customers.create form and the reservations.create form work with different tables. I've tried working with input types but I still get errors. I've spent a good day looking up what do to but I have not found anything that works yet.

My store function in my ReservationsController

    public function store(Request $request)
     {
         $data =[
           $request->customer_id,
           $request->room_no,
           $request->start_date,
           $request->end_date,
           $request->category,
         ];
       dd($data);
     }

My reservations table

    public function up()
        {
        Schema::create('reservations', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('room_no')->unsigned();
            $table->foreign('room_no')->references('room_no')->on('rooms');
            $table->date('start_date');
            $table->date('end_date');
            $table->decimal('amount')->default(0.0);
            $table->bigInteger('customer_id')->unsigned();
            $table->foreign('customer_id')->references('id')->on('customers');
            $table->string('category');
            $table->timestamps();
        });

My reservations.create.blade form

      <form method="POST" action="/reservations/">
        @csrf

        <div>
          <p>
               <b>Enter Reservation for  </b>
           </p>
           <h4 class="info-text">Select Room<br>
            <select name="room_no" id="room_no">
                <option value=100>100</option>
             //...there are more but no need to post ALL of them here
              </select>
           </h4>
            <h4 class="info-text">Select Room Type<br>
             <select name="category" id="category">
               <option value="Deluxe">Deluxe</option>
               // shortened for question's sake again
            </h4>
            <p>
        <b>Enter Start and End Date:</b>
           </p>
           <table>
               <tr>
                   <td>
                     <input class="input" type="date" name="start_date" size="11" />
                     <input class="input" type="date" name="end_date" size="11" />
                   </td>
               </tr>
           </table>
           <b>Cost of Stay</b>
           <td>
             <input class="input" type="decimal" name="amount" size="11"/>
           </td>
        <p><button type="submit">Create Reservation</button></p>
    </div>
  </form>

I am able to link my views with my routes

    Route::resource('reservations', 'ReservationsController');
    Route::get('/reservations/create/{customer_id}', 
     "ReservationsController@create_reservation");

When I dd in my controller, I should be getting all my data, including the customer_id, but when I run the application I get all my inputs except customer_id, which in this case is 0 in the array.

array:5 [▼
  0 => null
  1 => "106"
  2 => "2019-04-16"
  3 => "2019-04-30"
  4 => "Economy"
]

I'm sorry if I got too wordy or I posted too much code. I'm still kind of new to all of this. All and any help of any kind is appreciated, thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2ZGq3QW
via IFTTT

Images wont upload to public_html folder in Laravel Project

When i try to upload an image to my site, it stores in my storage folder, however, the symlink does not work so it doesnt save it in my public_html folder. I have tried using a custom symlink php file however it does not seem to do anything.

My symlinkcreate.php file

<?php
symlink('/home/jackdeaz/nscraft/storage/app/public', '/home/jackdeaz/public_html/storage');

my Filesystems.php file

'default' => env('FILESYSTEM_DRIVER', 'local'),

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

This is how i upload an image

$request->file('image_url')->store('public/img/products');

Any help would be greatly appreciated!



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2UHJoxq
via IFTTT

Update checkbox values in database

What is the best way to update records send from checkbox form. How to get to known which one have been unchecked.

My algorithm unset all values than goes again and check ids from request. Moreover it cause problem with timestamps, because all values are being updated every single time.

public function plansUpdate(Request $request){
        //set all plans as not default to handle unchecked
        $plans = $this->planService->getAllPlans()->pluck('id');
        PlanModel::whereIn('id', $plans)->update(['is_default' => false]);

        //set checked plans as default
        $defaultPlans = $request->get('default-plans');
        PlanModel::whereIn('id', $defaultPlans)->update(['is_default' => true]);

        return redirect()->back();
    }

I would like to perform better solution where only values changed in the form are being "touch" in the back-end.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2VucdBX
via IFTTT

Angular Login not responding - using Laravel backend

I use JWTAuth in Laravel. I developed a login page using Angular 7. Laravel 5.8 serves as the backend. I tested the api from Laravel using Post, it worked perfectly. I want the user to be redirected to Home Page after clicking the Sign in button on Login Page. The button did not redirect to anywhere

I tested the the Api from Laravel backend on Postman and it works. I also inspected the page and there is no error.

This is the flow: Laravel -> AuthenticationService(Angular)->Login(Angular)

proxy-conf.json

{
    "/api/*": {
        "target": "localhost/cloudengine-sandbox/cloudengine/public/api",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true,
        "pathRewrite": {
            "^api": ""
        }
    }
}

package.json

"start": "ng serve --proxy-config proxy.conf.json",

authentication.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';


  export interface UserDetails {
    id: number
    name: string
    email: string
    password: string
    username: string
    exp: number
    iat: number
  }

  interface TokenResponse {
      token: string
  }

  export interface TokenPayload {
      id: number
      name: string
      email: string
      password: string
  }

  @Injectable() 
  export class AuthenticationService {
    private token: string

    constructor (private http: HttpClient, private router: Router) {}

    private saveToken(token: string): void {
        localStorage.setItem('usertoken', token)
        this.token = token
    }

    private getToken(): string {
        if (!this.token){
            this.token = localStorage.getItem('usertoken')
        }
        return this.token
    }

    public getUserDetails(): UserDetails {
        const token = this.getToken()
        let payload
        if(token) {
            payload = token.split('.')[1]
            payload = window.atob(payload)
            return JSON.parse(payload)
        }else
        {
            return null
        }
    }

    public isLoggedIn(): boolean {
        const user = this.getUserDetails()
        if(user) {
            return user.exp > Date.now() /1000
        }else{
            return false
        }
    }


    public login(user: TokenPayload): Observable<any> {
        const base = this.http.post(
            '/api/login',
            { email: user.email, password: user.email},
            {
                headers:{'Content-Type': 'application/json'}
            }
        )
        console.log(user)
        const request = base.pipe(
            map((data: TokenResponse) => {
                if(data.token){
                    this.saveToken(data.token)
                }
                return data
            })
        )
            return request
    }    

  }

login.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthenticationService, TokenPayload } from '../../services/authentication.service';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent  {

credentials: TokenPayload = {
  id: 0,
  name: '',
  email: '',
  password: ''
}

constructor(private auth: AuthenticationService, private router: Router){}

login() {
  this.auth.login(this.credentials).subscribe(
    () => {
      this.router.navigateByUrl('/home')
    },
    err => {
      console.error(err)
    }
  )
}

}

login.component.html

        <form (Submit)="login()">
            <div class="alert alert-danger" [hidden]="!error">
              
            </div>
        <div class="form-group has-feedback">
            <input type="email" name="email" class="form-control" placeholder="Enter Email e.g. emailid@email.com" [(ngModel)]="credentials.email" required>
          <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
        </div>    

        <div class="form-group has-feedback">
          <input type="password" name="password" class="form-control" placeholder="Enter Password" [(ngModel)]="credentials.password" required>
          <span class="glyphicon glyphicon-lock form-control-feedback"></span>
        </div>
        <div class="row">
          <div class="col-xs-8">
            <div class="checkbox icheck">
              <label class="">
                <div class="icheckbox_square-blue" aria-checked="false" aria-disabled="false" style="position: relative;"><input type="checkbox" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div> Remember Me
              </label>
            </div>
          </div>
          <!-- /.col -->
          <div class="col-xs-4">
            <button type="submit" class="btn btn-primary btn-block btn-flat"> Sign In</button>
          </div>
          <!-- /.col -->
        </div>
      </form>

I expected that when I click the Login Submit button, it should redirect to /home, but nothing is happening. Note that I have already set home on app-routing.ts

What am I not getting right, and what do I do.

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2IMiRNN
via IFTTT

Is there any way to put OR condition in between two middlewares?

I have a situation where i wanna give access to both user and company for the same route using middleware.Is there any way i can user any condition like AND/OR in the middleware group. If anyone of them are authorized than can access the routes.

Route::group(['middleware' => ['auth','company']], function() { my routes });



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2GSQmMx
via IFTTT

helper vs controller performace in laravel 5.*

Lets assume I have a helper called engine.

if( ! function_exists('engine') )
{
    function engine($user_id_1, $user_id_2, $league, $log = true)
    {
        /*
         * variables
         */
        $questionsLevel = 1;

        $user1 = \App\User::where('id', $user_id_1)->first();
        $user2 = \App\User::where('id', $user_id_2)->first();

        $league = \App\Models\League::where('id', $league)->first();

        $users = $league->all_users;

        /*
         * check if users joined to league correctly
         */
         $user1_ok = $user2_ok = false;
         foreach($users as $user)
         {

             if( $user->id == $user_id_1 )
             {
                 $user1_ok = true;
             }
             if( $user->id == $user_id_2)
             {
                 $user2_ok = true;
             }

             $check_users = [
                 $user1_ok,
                 $user2_ok
             ];
         }

        if( in_array(false, $check_users) )
        {
            return [
                'errcode' => 404,
                'errmessage' => 'one ro both user/s did not joined to league'
            ];
        }

       //DO SOME STUFF

    }//function engine
}

As you know, I can write a controller to do same.

Does anyone know Which is faster based on Laravel architecture? and how can I test performance in both cases?

I'm using laravel 5.7.*



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2Vr1Crv
via IFTTT

What is the way to use the one query result in where clause in laravel like we do in sql query using where in clause?

I'm writing query in Laravel but its giving me error Saying

ErrorException: Object of class stdClass could not be converted to string

$subject_ids = DB::table('question_sets')
                   ->select('subject_id')
                   ->where('test_section_id','=',$testDetail->test_section_id)
                   ->distinct()
                   ->get();

$topic_ids = DB::table('topics')
                 ->select('id')
                 ->where('subject_id','=',$subject_ids)
                 ->get();



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2J0ioXz
via IFTTT

laravel 5.8 routes not working in xampp after update?

i have a pc and desktop, they both used to have xampp and laravel 5.7, recently i updated laravel to 5.8 in my desktop and reset laptop and install laravel 5.8,, routes are working all fine in desktop laravel version ,, but in newly installed laravel in laptop they aren't working, i get 404 error except '/' i tried override all, ifmodule solution they are all fine it is not working in newly installed laravel 5.8 please help ...

PS : i also created seprate project in desktop and laptop ,, not copy paste but individually created in both of them..

i checked apache hhtp.config for ifmodule and overrride and htaccess is default i haven't modified any and is same as all them in solution

i want to be able to use routes without using php artisan serve



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2DCp7Dw
via IFTTT

why datatables sorting is not working at right place?

I have posted picture. I am not getting datatables sorting on first tr tag. I have datatables individual column searching with select on second tr tag... but i want sorting on 1st tr tag and using scripts of theme dashboard working on theme but not woking on my project.Posted Picture for clear concept.

Image

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="">

Blade

<div class="card-content collapse show">
      <div class="table-responsive" id="searchResult">
          <table class="table table table-striped table-bordered base- 
          style" id="myTable">
    <thead class="table table-striped">
<tr>
    <th>Supplier Name</th>
    <th>Item Name</th>
    <th>Quantity</th>
    <th>Price</th>
    <th>Total</th>
    <th>Purchase Date</th>
    <th>Actions</th>
</tr>
<tr>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
</tr>
</thead>
<tbody>
@foreach($allPurchases as $purchase)
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td><a onclick="edit_purchases()"><i style="font-size: 18px" class="far fa-edit"></i>
            </a> | <a
                    href=""><i style="color: red;font-size: 18px" class="far fa-trash-alt"></i>

            </a>
        </td>
    </tr>
@endforeach
</tbody>
</table>
</div>
</div>

Script:

<script>
    var dataTableList = "";

    $(document).ready(function () {
        dataTableList = $('#myTable').DataTable({
            initComplete: function () {
                this.api().columns([0,1]).every( function () {
                    var column = this;
                    var select = $('<select><option value=""></option></select>')
                        .appendTo( $(column.header()))
                        .on( 'change', function () {
                            var val = $.fn.dataTable.util.escapeRegex(
                                $(this).val()
                            );

                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        } );

                    column.data().unique().sort().each( function ( d, j ) {
                        select.append( '<option value="'+d+'">'+d+'</option>' )
                    } );
                } );
            },
        });
    });
</script>



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2vqmyQP
via IFTTT