samedi 31 mars 2018

How can I implement Resource Controllers if I use many "get" on the laravel?

I have routes laravel like this :

Route::prefix('member')->middleware('auth')->group(function(){
    Route::prefix('purchase')->group(function(){
        Route::get('/', 'Member\PurchaseController@index')->name('member.purchase.index');
        Route::get('order', 'Member\PurchaseController@order')->name('member.purchase.order');
        Route::get('transaction', 'Member\PurchaseController@transaction')->name('member.purchase.transaction');
    });
});

My controller like this :

<?php
...
class PurchaseController extends Controller
{
    ...
    public function index()
    {
        ...
    }
    public function order()
    {
        ...
    }
    public function transaction()
    {
        ...
    }
}

I want to change it to Resource Controllers(https://laravel.com/docs/5.6/controllers#resource-controllers)

So I only use 1 routes

From my case, my routes to be like this :

Route::prefix('member')->middleware('auth')->group(function(){
    Route::resource('purchase', 'Member\PurchaseController');
});

If I using resouce controller, I only can data in the index method or show method

How can I get data in order method and transaction method?



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

Laravel - how can make dynamic content with layout?

I'm wanting to create a website with laravel framwork. I had made layout but now, have some zone i don't know how to set content for it. Ex: 2 zone of me are left-menu and cart (please view picture). My left-menu will get content from table: categories and cart will get content from package cart [Cart::content()]. It's on layout and of course, all page will have it. But i don't know how to give content of categories and cart() for it. Please help me left-menu and cart



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

Laravel Issue with Duplicate Mailings of Mailable

I have, what appears to me, to be the oddest error and I am hoping someone here can sniff out where my faux pas in my code is.

I have a table of records on a blade, where each record is a row with a checkbox (the name being send[]).

This is not where I am having my issue, but to describe it, when I click a button, it sends off the values of the checkboxes to my controller function, these values are all records values from the default ids in my MySQL table.

NOW, my actual problem lies somewhere in the controller or somewhere I cannot see, but there is an issue that shouldn't be happening no matter what.

This is the function I am referring to:

public function sendNow(Request $request)
    {
        $now = Carbon::now();
        $sendNowShipment = array();
        $method = array();
        $sendNowShipment = request('send');
            foreach($sendNowShipment as $SNS){
                $shipment = Shipment::findOrFail($SNS);
                $shipment->billedAt = Carbon::now();
                $shipment->save();
                if($shipment->billtoAccount->billingMethods->label == "Mail"){
                $timestamp = Carbon::now()->timestamp;
                $shipment_details = $shipment->shipment_details;
                    $path = 'temp/freightbill_'.$shipment->pro_number.'-'.$timestamp.'.pdf';
                    $sessionPath[] = $path;
                    $pdf = PDF::loadView('shipments.pdf', compact('shipment', 'shipment_details'))
                        ->save($path);
                }elseif($shipment->billtoAccount->billingMethods->label == "Email"){
                    $billToAccount =   $shipment->billtoAccount;
                    $billToAccountUsers = $billToAccount->users;
                        if ($billToAccount->car_billingEmail){
                            $billToEmail[] = $billToAccount->car_billingEmail;
                        }
                        if ($billToAccountUsers->count() > 0){
                            foreach ($billToAccountUsers as $billToAccountUser){
                                $billToEmail[] = $billToAccountUser->email;
                            }
                        }
                        foreach ($billToEmail as $bte){
                            Mail::to($bte)->send(new newBillToShipment($shipment));
                        }
                }
            }

////////Everything below doesn't appear to affect the issue//////
        $sendShipment = array();
        $method = array();
        $sendShipment = request('send');
            foreach($sendShipment as $ss){
                $shipmentSend = Shipment::findOrFail($ss);
                $method[] = $shipmentSend->billtoAccount->billingMethod;
            }

        $counts = array_count_values($method);
        if (array_key_exists(1, $counts)) {
            $countsPrint = $counts[1];


        if($countsPrint > 0){
            $pdf = new PDFMerger();

            // Add Generated PDFs to the final PDF
            foreach($sessionPath as $sp){
            $pdf->addPDF($sp, 'all');
            }

            // Merge the files and retrieve its PDF binary content
            $timestamp = Carbon::now()->timestamp;
            $binaryContent = $pdf->merge('download', $timestamp."-printBatch.pdf");

            // Return binary content as response
            }
        }
        return back();
    }

To be clear, if the problem is in the function, then it must be between the top of the code and about the middle where I place the note.

Now the problem pops up around this line $shipment->billtoAccount->billingMethods->label == "Email", as it's all focused on the email aspect of this function. If you look through the code, you'll see something about if the billtoAccount has users to pull their emails in as well.

However, this is not the problem. For whatever reason, and I can share screenshots if necessary, I will go through the timeline of events.

I've known about this issue for a while but was only made aware of it after the most recent update I did of Laravel and wonder if it's something there.

I go to click the send now of four (4) records that are email only. Their respective numbers are 9433, 9437, 9438 and 9439.

The button only sends out the one request along with the array of four record ids.

Each one of these belongs to the same account, which has no users included in it, so that portion about the users shouldn't count here and they do have only one billing email (the car_billingEmail field).

After a few seconds, the screen returns back to the original screen.

However, while 8 emails should have been sent out (4 to the customer, one for each invoice, and 4 to me for archival purposes), if I go to Sparkpost (where I handle the emails through), it reports that it sent out about 12 emails.

If I go to my inbox, I see that for two invoices I received one email each, one invoice received two and one received three emails.

Now, given that these are all the same customer, I would've understood receiving the same amount for each invoice (even if it was more than one), but given that the numbers are scattered, I am extremely confused.

What's more is that I know this is not Sparkpost's doing, as I send out other emails through them for other purposes on the site and I don't have these issues.

If you need anymore information or code or whatever, feel free to ask, I'd just really like to fix this issue before I am driven to insanity trying to make sense of it.

Thanks!!!

Matt



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

Laravel View Composer with View Component and One To Many Relationship

In short, I am wondering if there is a better way of using view composers than my current setup.

I have a ComposerServiceProvider with the following boot() code:

view()->composer(['components.carousel'], function ($view) {
    $carousels = Carousel::with('slides')->get();
    $view->with(compact('carousels'));
});

My component is pretty straightforward:

<style type="text/css">
  .carousel-item {
    height: 100vh;
    min-height: 300px;
    background: no-repeat center center scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  }
  .carousel-caption {
    background-color: rgba(0,0,0,0.1);
    top: 40%;
    bottom: unset;
  }
</style>

@php
  $carousel = $carousels->filter(function ($carousel, $key) use ($name) {
    return ($carousel->name == $name);
  });
@endphp

<header>
  <div id="carouselIndicators" class="carousel slide" data-ride="carousel">
    <ol class="carousel-indicators">
      @foreach ($carousel[0]->slides as $slide)
        <li data-target="#carouselIndicators"
            data-slide-to=""
            class=""></li>
      @endforeach
    </ol>
    <div class="carousel-inner" role="listbox">
      @foreach ($carousel[0]->slides as $slide)
        <div class="carousel-item "
             style="background-image: url('')">

          @if ($slide->title || $slide->description || $slide->link)
            <div class="carousel-caption d-none d-md-block">
              <h3></h3>
              <p></p>
              <a class="btn btn-primary btn-sm" href="">Learn More</a>
            </div>
          @endif

        </div>
      @endforeach
    </div>
    <a class="carousel-control-prev" href="#carouselIndicators" role="button" data-slide="prev">
      <span class="carousel-control-prev-icon" aria-hidden="true"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#carouselIndicators" role="button" data-slide="next">
      <span class="carousel-control-next-icon" aria-hidden="true"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</header>

To use the component:

@component('components.carousel', [
    'name' => 'Super Awesome Carousel'
])
@endcomponent

What is bothering me is this piece:

@php
  $carousel = $carousels->filter(function ($carousel, $key) use ($name) {
    return ($carousel->name == $name);
  });
@endphp

I am returning every carousel WITH the slides relationship and then filtering the carousels and only using the one carousel->slides relationship I need. Is there a way of letting the view composer know the name of the carousel I need? Or is there a better way of approaching this?

Thanks,



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

Laravel Union 2 Tables

I have the following custom builder (I need to supply a builder instnace to a package that I use)

public function query()
{
    $connection = $this->getConnection();

    return $connection->table(
        $connection->raw('(' . $this->mainQuery()->toSql() . ') abc')
    )->select('*');
}

public function mainQuery()
{
    $q1 = $this->firstQuery();
    $q2 = $this->secondQuery();

    return $q1->unionAll($q2);
}

private function firstQuery()
{
    return $this->topic
        ->where('title', 'LIKE', '%'.'test'.'%')
        ->select(['message', 'created_at']);

}

private function secondQuery()
{
    return $this->reply
        ->where('message', 'LIKE', '%'.'test'.'%')
        ->select(['message', 'created_at']);
}

Doing a

 $builder = app(QueryBuilderHelper::class);
 $query = $builder->query();
 return $this->applyScopes($query);

results in

General error: 2031 (SQL: select count(*) as aggregate from (select * from ((select `message`, `created_at` from `topics` where `title` LIKE ? and `topics`.`deleted_at` is null) union all (select `message`, `created_at` from `replies` where `message` LIKE ? and `replies`.`deleted_at` is null)) abc) count_row_table)"}

I don't see what the issue is..



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

Too Many Redirects when accessing non laravel files

i am new to laravel and using version 5.0.16. I have just added new phpfiles not necessarily part of the same laravel mvc framework..i get this error when attempting to access the files:

redirected you too many times.

they are stored under my 'public_html' folder



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

Laravel Broadcast putting details on Logs

I am trying to implement Broadcast with pusher . Everything works fine when I tested it on the local host . But as soon as I uploaded the files on Server , broadcast started to put the data on the Logs instead of pushing it to pusher.

Here is my Event

class MessageReceive implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $message, $sender , $id;

    public function __construct(Messenger $data)
    {
        $this->message = $data->message;
        $this->sender = $data->people_id;
        $this->id = $data->user_id;
    }

    public function broadcastOn()
    {
        return new Channel('message.' . $this->sender);
    }

    public function broadcastAs()
    {
        return 'MessageReceive';
    }

    public function broadcastWith()
    {
        return [
            'id' => $this->id,
            'sender' => $this->sender,
            'message' => $this->message,
            'time' => now(),
        ];
    }

}

Here is what I get on my log file..

[2018-03-31 18:34:35] local.INFO: Broadcasting [MessageReceive] on channels [message.1526560620] with payload:
{
    "id": "1",
    "sender": "1526560620",
    "message": "hey buddy",
    "time": {
        "date": "2018-03-31 18:34:35.000000",
        "timezone_type": 3,
        "timezone": "UTC"
    },
    "socket": null
} 

I did tried to restart the queue , but it doesn't seems to work



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

Laravel Botman Studio

I've installed botman studio on my existing laravel project to create a chat bot. The chatbot works. However, im looking for complex conversations where user can ask chatbot "What is Example" and Chat box searches from the database table and answers back.

I do not find any tutorial or links that can help me get started. Does anyone know how to do this? A simple example could help me



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

DOMDocument doesn't grab prices by country

Laravel 5.4

I use DOMDocument for grabbing prices from the gearbest.com. In Lithuania country the gearbest shows lower products price, than original ones.

In website page I see price 428.17Eur:

<span class="my_shop_price new_shop_price ajax-price-main" data-key="705268#37" data-shopprice="521.67" data-orgp="521.67" id="unit_price" style="visibility: visible;">€428.<i>17</i></span>

But from DomDocument I get 521.67 Eur price:

&lt;span class=&quot;my_shop_price new_shop_price ajax-price-main&quot; data-key=&quot;705268#37&quot; data-shopprice=&quot;521.67&quot; data-orgp=&quot;521.67&quot; id=&quot;unit_price&quot;&gt;$521.&lt;i&gt;67&lt;/i&gt;&lt;/span&gt;&amp;#xD;<span class=sf-dump-default>\n</span>

I rent server in Lithuania.

Maybe need send country code in header? I don't know. Please help me.



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

how to post the data of the client entered during registration into WHMCS using laravel

I have entered the controller and route code below and suggest me a solution to post the datas into WHMCS.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\ProductController;


use Illuminate\Http\Request;

use DarthSoup\Whmcs\Facades\Whmcs;
use Darthsoup\Whmcs\WhmcsServiceProvider;

use WHMCS\Database\Capsule;

class ProductController extends Controller
{
public function insertform(){
    return view('clientlayout.main.signup');
    } 


 public function insert(Request  $request)
 {
  $request=array();
    $request["firstname"] = $_POST['firstname'];
    $request["lastname"]=  $_POST['lastname'];
    $request["companyname"] =  $_POST['companyname'];
    $request["email"] =  $_POST['email'];
    $request["address1"] =  $_POST['address1'];
    $request["address2"] =  $_POST['address2'];
    $request["city"] =  $_POST['city'];
    $request["state"] =  $_POST['state'];
    $request["postcode"] =  $_POST['postcode'];
    $request["country "]=  $_POST['country'];
    $request["phonenumber "]=  $_POST['phonenumber'];
    $request["password"] =  $_POST['password'];

        $whmcs = Whmcs::create($request); 
        return redirect()->route('whmcs.detail', ["firstname" => $whmcs- 
        >firstname]);      

        print_r($request);

           echo '<a href = "/insert">Click Here</a> to go back.';

     }
     }

The logic in blade file is given below:

 <form class="container" action="" id="needs- 
  validation" method="post" novalidate>
    <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); 
  ?>">

My route code is given below:

Route::get('insert', 'ProductController@insertform');
Route::post('insert', 'ProductController@insert')->name('product.insert');

Give me an idea in storing the data entered by the client during registration into WHMCS, as I'm having an issue in Storing it in WHMCS.



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

How to override the 'create' method when inserting into a related model. Laravel 5.5

I want to insert a new event (like a party ...etc) that is related to a user, so I do this according to this tutorial:

$event = $owner->events()->create( $request->all() );

However, I'd like to override the create method before inserting so according to this tutorial I do this in the app\Event:

public static function create(array $attributes = [])
        {
            error_log('Im here.');
            if ($attributes->privacy === "private") {
                /////
            }

            else {
                /////
            }

            $event = static::query()->create($attributes);

            return $event;
        }

My issue is that the code never reaches the new create method.



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

Re-using custom laravel commands

I have created my own commands using php artisan make:command CommandName this suits my needs so I want to include it in other projects. Is there some way to do this using composer commands?



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

Could not get user id from Laravel controller

When I want to get the logged in user id using Auth::user()->id from the controller then, it gives this error.

HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request. (XHR)POST - http://leadmanager.dev/api/treatment/add

If I type the user id manually it works and gets saved to the database, also Auth::user()->id works for GET requests but not for post requests. All relations between the tables are completed. Has anyone faced this issue?

My code

<?php

namespace App\Http\Controllers;

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

class TreatmentsController extends Controller
{
    //Post request 
    //Add Treatment
    public function add(Request $request){
        $treatment = new Treatment;
        $treatment->name = $request->treatmentName;
        $treatment->user_id = Auth::user()->id;
        $treatment->company_id = Auth::user()->company->id;
        $treatment->save();
      }

}


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

How to handle this error : Class App\Http\Controllers\post/ProductController does not exist

Code in the blade file is given as below:

@extends('clientlayout.layouts.master1')
@section('title')
Register
@endsection
@section('content')
<div class="container" style="background-color: #c1bdba;max-width: 100% 
!important;">
<div class="row">
  <div class="offset-lg-2 col-lg-8 col-sm-8 col-8 border rounded main- 
  section"  style="background-color:rgba(19, 35, 47, 0.9);">
  <img src="client/images/decksys.png" alt="." style="margin: 20px 0px 20px 
350px;"> 
    <hr>
    <form class="container" action="/create" id="needs-validation" 
method="post" novalidate>
    <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); 
 ?>">
      <div class="row">
        <div class="col-lg-6 col-sm-6 col-12">
           <div class="form-group">
            <label class="text-inverse custom" 
 for="validationCustom01">First Name
 <span class="req">*</span>
 </label>
<input type="text" name="firstname" class="form-control" 
id="validationCustom01"  placeholder="First name"
value="" required maxlength="25" onKeyPress="return ValidateAlpha(event);" 
style="background-color: rgba(19, 35, 47, 0.4); color:#fff;">
            <div class="invalid-feedback">
              Enter Your Firstname
            </div>
          </div>
        </div>

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

The Controller code is shown below:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\ProductController;


use Illuminate\Http\Request;

use DarthSoup\Whmcs\Facades\Whmcs;
use Darthsoup\Whmcs\WhmcsServiceProvider;

class ProductController extends Controller
{
 public function insertform(){
    return view('clientlayout.main.signup');
    } 

  public function insert(Request $request){

    $user = User::create([
        'firstname' => $data['firstname'],
        'lastname' => $data['lastname'],
        'email' => $data['email'],
        'city' => $data['city'],
        'dob' => $data['dob'],
        'password' => bcrypt($data['password']),
    ]);
    Whmcs::create($data->all());
    return redirect($this->create());

    echo "Record inserted successfully.<br/>";
    echo '<a href = "/insert">Click Here</a> to go back.';

    }

    }

The route code is given below and suggest me if any changes has to be made in the route.

Route::get('insert', 'ProductController@insertform');
Route::post('create','post/ProductController@insert');

Suggest me a solution to handle this error - "Product Controller doesn't Exit" and to get the output as follows:

Record inserted successfully



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

Can't login to two laravel project in same browser another log out

I am working on the Laravel project 5.3 and the problem I am facing is when I log in to frontend or the admin Panel another session destroy and logouts the application, need some solution. Both are running on different ports like

  1. example.com
  2. example.com:75/public
  3. example.com:81/public

I am extremely sorry for the bad English and thank you in advance.



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

vendredi 30 mars 2018

Laravel pass data between views

I have a view with a few variables that I want to pass to a new page and prepopulate a form with them.

$data->title
$data->catid
$data->category
$data->groupName

The "vanila way I could make a url like something.com?var1=something&var2=something etc.

But how can I do this in laravel?



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

Laravel 5.5 - SerializesModels on event causes ModelIdentifier error?

I have a laravel event with a few listeners. Some listeners or their notifications (depending if they are time consuming) are implementing the ShouldQueue so they run in the background on a redis queue. The event uses SerializesModels by default, but when one of the passed models to the event is the logged in user and we fire it, like this:

$user = $this->user(); // logged in user instance
event(new UserCreatedPost($user, $post, $modelX, $modelY));

I am not able to access the user's followers in the respective listener, to check whether or not to notify them if they exist:

// In listener handle method
public function handle(UserCreatedPost $event){
    $followers = $event->user->followers()->get();
}

I get this error:

Call to undefined method Illuminate\Contracts\Database\ModelIdentifier::followers()

The only way I was able to get it to work was to add event wakeup below:

public function handle(UserCreatedPost $event){
    // This fixes it, as it unserializes all the models
    // (even though we only need this model to be unserialized, not all of them)
    $event->__wakeup();


    $followers = $event->user->followers()->first();
    // If at least one follower exists send queued notification
    // else exit
}

I do use the $user instance in a few other listeners under the same event and other event listeners. I don't even know if the $user should be serialized in the first place at all, but it is a model, so the parent event SerializesModels trait automatically serializes all the models (and I don't know of any way to make this specific model not be serialized while other models yes).

Is there a better way to be able to access the $user in the listeners without having to do the wakeup call at all? I have many events with listeners, and just got to implementing queues now, so I really don't want to add that wakeup to all areas in all files that the error would appear, but I do want to queue some of the listeners or their notifications. An alternative would be to remove the event SerializesModels trait and not even worry about that error showing up under this or any other listener I have yet to discover this error in. Are there any issues that can arise, like performance for example or others, by implementing the alternative approach? Any better way?



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

Sub domain routing gives a permission error

I am trying to configure sub-domain routing for my laravel web application.

What I am doing in web.php looks like:

Route::group(['domain' => 'example.in'], function () {

Route::get('/', 'CustomController@showWelcomePage');
});

Route::domain('{account}.example.in')->group(function () {
Route::get('event-organizer/{account}','CustomController@getOrganizerPage')->name("sub_domain");
});

and in my custom controller:

public function showWelcomePage() {

    $eventData = Event::all();

    return view('welcome')->with('eventData', $eventData);
}

 public function getOrganizerPage($account) {

    $organizer_name = User::where('org',$account)->first();

    $eventData = Event::where('user_id', $organizer_name->id)->get();
    return view('single_organizer_page')->with('eventData', $eventData);
}

and my .htaccess file looks like:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>

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} (.+)/$
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.in/$1 [R=301,L]


# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

</IfModule>

I am able to create sub domain dynamically successfully but whenever I hit the url

http://testorg.example.in/

I get a error saying this:

Forbidden You don't have permission to access / on this server. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

I don't know where am I going wrong!!



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

Laravel eloquent patter search not working properly

I am trying to query database using the user input value for search field. But the result i am getting is totally wrong. It doesn't have the search term. I have no idea where i could be doing wrong. i followed the laravel doc,and some questions over stackoverflow, but nothings seems to be working. Can anyone please check my query and perhaps can guide me to the right direction.

My query is like this Query term is Rose , and only one record has title name Rose

public function catelogSearch(Request $request){

    if ($request->has('query') && $request->get('query')!= ''){
        $searchQuery = $request->get('query');

        $query = ProductCategory::with(['product'=>function($q) use($searchQuery){
            $q->where([
                ['product_type','both'],
                ['title','LIKE','%'.$searchQuery.'%'],
                ]);

            if(request()->segment(1)=='shopping'){
                $q->orWhere('product_type','shop');

            }elseif (request()->segment(1)=='subscription'){
                $q->orWhere('product_type','sub');
            }
            $q->whereHas('price',function ($q){
                $q->where('quantity','>',0);
                $q->where('status',1);
            });
        }])->with('product');

                $data['result']=$query->paginate(30)->toArray();

            print_r($data);

}

This query giving me all the data in my database, unlike where it should give me where it has the query term in the title. And also please see, that i am querying with('product') two times. If i do one time, It doesn't return product data, it return empty response for the product.

Can anyone please suggest me. Thank u.



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

Multi Language Approach - Advice Needed

I'm creating a portal where i have users, questions (just like laracasts), articles and businesses

Now im creating this in more than 40+ languages so im planning to store the translations in the database. For example i have created articles and article_translations table and storing each article in multiple language in the article translations table. Now i have to do the same for users, questions and businesses.

So i created profiles table where i have a type field(user, business) and fields as per the user choice are displayed on the form. All fields are nulled. The problem is a user will have a profile in 40+ languages which means each user will have 40+ entries for his profile(english, spanish, italian and so on).

This works fine for me and im able to translate the whole website. However, im confused if this is the right approach as if in future the site gets big and has huge users the database would be more huge.

Any experts in here who could suggest me if i can go with this approach or will this be a problem for me in the future.

Note: This approach has given me ability to translate the whole site to preferred language.



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

Laravel 5.5 - Horizon custom job tags for queued event listener

In the documentation for Horizon, it mentions that custom tags can be added to queued event listeners. However, I can't find any way to pull in my event instance containing the data I need. The example given uses type-hinting to pull the relevant model out of the service container and assigns it to an instance variable in the constructor, then uses that instance variable in the tags() method to get data about the particular model instance being operated on.

When doing this in a queued event listener though, it doesn't work. In fact, the constructor doesn't ever seem to be called at all, due to the model being serialized and 're-hydrated' when it comes to be executed. So type-hinting in the constructor does nothing, and tags() appears to be called before handle(), so I can't get access to the event object I'm listening to.

Does anyone know how I can get event information in a tag in this situation?



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

Laravel : Nested relation search

I have two nested relations, One is requester.link and requester.company, I want both to be search for the word $request->search.

The code is self explanatory:

$clients = \App\AcceptedConnection::with('requester.link', 'requester.company')
    ->where('accepter_id', Auth::user()->id)
    ->orWhereHas('requester.link', function ($query) use ($request) {
        $query->orWhere('name', $request->search);
    })->orWhereHas('requester.company', function ($query) use ($request) {
        $query->orWhere('email', $request->search);
        $query->orWhere('firstname', $request->search);
        $query->orWhere('lastname', $request->search);
    })->get();

It gives me the records for anything searched, It returns records even the search is not matching, Search anything and it will give you records,

What am i missing ?



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

Reset password bot working properly in laravel

I am working on a project in Laravel, In my project login, registration, send forget password mail working fine. But when I am trying to reset the password Every time I am getting error.

This password reset token is invalid.

I have no idea, Why I am getting this error. Just noticed that Every time in token hidden field I am getting the same value

Wbkv7yreu4YKvNL4Lv2vYaqlpJW7BoJycjQxew4u

Is there any easy solution? If not then How can overwrite the build-in reset password functionality?



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

Laravel - View with multiple attributes, URL only with ID

I'm trying to give attributes to a view (So i can use them in blade) while in the route it only requires the ID. let me explain

The route I'm talking about is Route::get('/order/{id}', 'OrderController@show'); now in that particular show method, I want to return a view with the $order variable another variable called $payment which consists of some information. So that I can use them in blade. Thats show method looks like this

public function show(Order $order, $payment)
{
    return view('orders.show', compact('order', 'payment'));
}

In that same controller I have a store method and when everything inside that method is executed it redirects to the show method by doing this

return $this->show($order, $payment);

But when the store method is executed and the order is shown. The URL is order/26/store instead of order/26. presumably because I use

return view('orders.show', compact('order', 'payment')); in the show method.

How can I make it so I can use both the variables (In blade) while the route looks like 'order/26' Instead of order/26/store

Both routes I'm talking about are listed here.

Route::get('/order/{id}/store', 'OrderController@store')->name('storeOrder');
Route::get('/order/{id}', 'OrderController@show')->name('showConfirm');



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

Laravel ajax returns undefined value

I have an dropdown that I want it to make dynamic. In my example, a service has many categories and a categories belongs to a specific service. When a dropdown service is selected. It will display only all the categories that belongs to that service in the second dropdown.

So here's what I have done so far.

In my fields.blade.php

<!-- Client Id Field -->
<div class="form-group col-sm-6">
    {!! Form::label('client_id', 'Client Name:') !!}
     {!! Form::select('client_id', $client, null, ['class' => 'form-control','required'])!!}
</div>

<!-- Service Id Field -->
<div class="form-group col-sm-6">
    {!! Form::label('service_id', 'Service:') !!}
     {!! Form::select('service_id', $services, null, ['class' => 'form-control','required'])!!}
</div>

In my JS script

$(function() {
            $('#service_id').change(function() {

                var url = '' + '/service/' + $(this).val() + '/categories/';

                $.get(url, function(data) {
                    var select = $('form select[name= category_id]');

                    select.empty();

                    $.each(data,function(key, value) {
                        select.append('<option value=' + value.id + '>' + value.name + '</option>');
                    });
                });
            });
        });

In my routes web.php

Route::group(['prefix' => 'encoder','namespace' => 'Encoder'], function () {
Route::get('service/{service}/categories', 'ServiceController@getCategories');
});

In my ServieController.php

public function getCategories($idService)
    {
        if(!is_numeric($idService)) abort(404);

        $service = Service::findOrFail($idService);
        return $service->categories->pluck('name', 'id');
    }

I think I am already fetching the right data because when a specific service has 2 categories. It returns me also 2, but the value is undefined in the dropdown.

Appreciate if someone could help. Thanks in advance.



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

jeudi 29 mars 2018

cannot execute php artisan command [php fatal error[

enter image description hereI have a laravel project I installed the composer and run

composer install

After that I executed the update command

composer update

on the project's root directory, and during the execution on the command

php artisan optimize

I got the error shown in the attached image.

When I try to execute any php artisan command I got the same error too.

Error lines

PHP Fatal error:  Uncaught Error: Call to undefined method Illuminate\Support\Facades\Auth::check() in C:\xampp\htdocs\projectx\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:221
Stack trace:
#0 C:\xampp\htdocs\projectx\app\Exceptions\Handler.php(39): Illuminate\Support\Facades\Facade::__callStatic('check', Array)
#1 C:\xampp\htdocs\projectx\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php(81): App\Exceptions\Handler->report(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#2 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#3 {main}
  thrown in C:\xampp\htdocs\projectx\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 221
PHP Fatal error:  Uncaught Error: Call to undefined method Illuminate\Support\Facades\Auth::check() in C:\xampp\htdocs\projectx\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:221
Stack trace:
#0 C:\xampp\htdocs\projectx\app\Exceptions\Handler.php(39): Illuminate\Support\Facades\Facade::__callStatic('check', Array)
#1 C:\xampp\htdocs\projectx\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php(81): App\Exceptions\Handler->report(Object(Symfony\Component\Debug\Exception\FatalErrorException))
#2 C:\xampp\htdocs\projectx\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php(123): Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Symfony\Component\Debug\Exception\FatalErrorException))
#3 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown()
#4 {main}
  thrown in C:\xampp\htdocs\projectx\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 221



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

Retrieve file uploaded in Laravel using JavaScript FormData

Running into a bit of trouble trying to upload multiple files through a single AJAX request into a Laravel 5 back-end.

In the front-end, I am using the following code to prep the FormData object:

var fd = new FormData();
fd.append("data", JSON.stringify(values));
fd.append("page_id", page_id);
files.forEach(function(file, index){
    fd.append("file_"+index, file);
});

Then this is my AJAX call:

$.ajax({
    type: 'POST',
    url: '/file_test',
    data: fd,
    contentType: false,
    processData: false,
    success: function(response){
        alert(response);
    },
    failure: function(response){
        alert(response);
    }
});

In the back-end, I've tried to retrieve with $request->allFiles() and $request->file('file_0') but they are both turning up empty.



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

Laravel update function throws exception

I am currently working with laravel and want to update 'Model' with a controller

public function update(Request $request, $id)
{
    $request->validate([
        'criminal' => 'required|string',
        'crimes' => 'required|string',
        'happened_at' => 'required',
        'description' => 'required|string',
        'report' => 'string|nullable',
        'happened_at' => 'required',
        'testifies' => 'string|nullable',
        'officers' => 'string|nullable',
    ]);

    $case               = Cases::find($id);
    $case->criminal     = $request->input('criminal');
    $case->crimes       = $request->input('crimes');
    $case->officers     = $request->input('officers');
    $case->testifies    = $request->input('testifies');
    $case->report       = $request->input('report');
    $case->happened_at  = $request->input('happened_at');
    $case->crime_desc   = $request->input('description');

    $case->save();
    return redirect('cases.index');
}

It does not save the data and throws an exception:Unexpected data found. Unexpected data found. Data missing

Does somebody know why it throws an exception? Thank you in advance



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

Laravel 5.5 Try / Catch is not working it's execute the exception handle

I am working with laravel 5.5 I have written a code with try and catch exception. But Try / catch is not manage exception handling. Exception execute on the Exception/handle.php

Here is code I am following

try {
 App\Models\justDoIt::find(1);
}  catch (\Exception $ex) {
       dd($ex);
       report($ex);
       return false;
}

I would like to know why catch is not executed and trow error to the handle.php in report()

Here is the handle.php code

public function report(Exception $exception) {
        echo "Handle";
        dd($exception);
        parent::report($exception);
    }

Result

Handle
FatalThrowableError {#284 ▼
  #message: "Class 'App\Http\Controllers\App\Models\justDoIt' not found"
  #code: 0
  #file: "D:\xampp7\htdocs\homeexpert_nik\app\Http\Controllers\HomeController.php"
  #line: 21
  #severity: E_ERROR
  trace: {▶}
}

Result will show from the handle.php file.



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

Laravel - select with relationship with one query

I have a Person model. Each person may have zero or more cars:

class Person extends Model
{
    public function cars()
    {
        return $this->hasMany('App\Car');
    }
}

I wish to select and display all persons who have a ford with one running query. So i tried this:

$persons = Person::whereHas('cars', function ($query) {
    $query->where('mark', 'ford');
})->get();

foreach ($persons as $person) {
    foreach($person->cars()->get() as $car) {
        print $person->name . " has a " . $car->mark . $car->model
    } 
}

The $persons is gotten with one query, but inside the foreach loop $person->cars()->get() creates a new query for each person. How can i avoid this and get the needed car data with the first query?



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

How do I get the ID in my request validation

How can I get the ID from the request, if is a new register, I want it to be null or 0

I need this to do custons validations, one validation for create and another for update

that is my Request

class PortifolioRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'nome' => 'required|max:255',
            'url' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'nome.required' => 'O nome é obrigatório',
            'nome.max' => 'O tamanho máximo para nome é de 255 caracteres',
            'url.required' => 'A URL é obrigatória',
        ];
    }
}



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

Laravel - Sort By Eager Loading Results

I am extremely new to eager loading and have run into what I assume to be a simple problem of me just not understanding it. I reviewed some of the materials here: https://laravel.com/docs/5.6/eloquent-relationships#eager-loading and have looked around but can't seem to get maybe the right terminology for what I am asking.

At the moment in my equipment model I have the following relationship:

public function registrationsExpireLatest()
{
       return $this->hasOne(EquipmentLicense::class,'equipmentID','id')
    ->orderByDesc('expirationDate');
}

This works perfectly, but say I want to put it on an index blade under an @foreach, I get everything I need, including the expiration date using the code below:

        @foreach ($equipments as $equipment)

             <tr>
                 <td><a href="/origins/"></a></td>
                 <td></td>
                 <td>@if (count($equipment->registrationsExpireLatest))
                     
                    @endif</td>
            </tr>

        @endforeach

Coming from this controller code:

    $equipments = Equipment::with(['registrationsExpireLatest' => function ($query) {
                                    $query->orderBy('expirationDate', 'asc');
                                }])
                                ->where([
                                    ['unit_type','<',3],
                                    ['active','=',1]
                                    ])
                                ->limit(10)
                                ->get();

Which all outputs like this:

11      086-YRR     2015-05-31
26      062-XWE     2018-11-30
33      880-HNV     2018-04-30
39      820-YYT     2018-01-31
203     279-WWU     2013-12-31
31      BMR 199     2018-04-30
UNK3    997-WLH     2011-09-30
1       957-VDN     2018-05-31
1096    187-MFF     2015-01-31
2105    154-CLU     2018-01-31 

As you can see by my controller, I tried sorting already in what I thought was the proper way put out here: https://laravel.com/docs/5.3/eloquent-relationships#constraining-eager-loads

But as you can see from my results table, they are out of order according to the expiration date.

I'd like it to go earlier (as in 2011) to later (as in 2018) by date. Is there a way of doing this?



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

Render from another controller method

I'm using Laravel 5.5 version and I have a question.

Let's say that my controller has 2 methods like this:

public function errorsCheck(){
    return view('errors_check');
}

public function index(){
     $this->errorsCheck();
     // some other important code
}

And when I open my webpage it goes to index() method first. Then it calls errorsCheck(). And errorsCheck() has to render view file and stop script executing.

How can I do it? I can't make something like:

return $this->errorsCheck();

because I need code above to execute if errorsCheck method doesnt found any errors. And this is not validation errors, btw.

Any ideas? Thanks.



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

laravel 5.5 Multi auth error 'InvalidArgumentException Authentication user provider [] is not defined

The error is

InvalidArgumentException …\vendor\laravel\framework\src\Illuminate\Auth\CreatesUserProviders.php42

config/auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'adminss',
        ],
    ],

Here's my provider array

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admins' => [
            'drivers' => 'eloquent',
            'model' => App\Admin::class,
    ],

],

This is my Admin model

class Admin extends Authenticatable
{
    use Notifiable;

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

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

    protected $table = 'admins';


}

This worked in laravel 5.4 but I'm getting error in 5.5



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

Laravel - Pull only Most Recent Record Value into Index Blade @foreach

In my index blade of equipment, I have the following lines:

            @foreach ($equipment as $equipment)

                 <tr>
                     <td><a href="/origins/"></a></td>
                      <td></td>
                      <td></td>
                     <td></td>
                     <td></td>
                     <td></td>
                </tr>

            @endforeach

As you can see, the last column pulls in "registrations". As they sit now, they arrive as an array such as below:

[{"id":45,"equipmentID":368,"amountDue":"0.00","emissions":0,"createdBy":1,"created_at":null,"updated_at":null,"expirationDate":"2015-05-31"},{"id":63,"equipmentID":368,"amountDue":"0.00","emissions":0,"createdBy":1,"created_at":null,"updated_at":null,"expirationDate":"2014-03-31"},{"id":274,"equipmentID":368,"amountDue":"1594.57","emissions":0,"createdBy":1,"created_at":null,"updated_at":null,"expirationDate":"2012-11-30"}]

How would I go about sorting it so the record with the most recent "expirationDate" comes first and the date itself is the thing printed to the index (in the above case, I'd be looking for the date 2015-05-31).

Would this be an attribute through the model?

Before I forget, my current relationship between the two models (the equipment and the registrations) is defined as such:

public function registrations()
{
    return $this->hasMany(EquipmentLicense::class,'equipmentID','id');
}

Thanks!



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

Laravel 5.1 factory definition unable to resolve closure for foreign relationships

I'm having trouble defining the factory function to handle foreign relationships for my business model. This is the code for my business model factory. The error message that I am getting is :

Uncaught exception 'ErrorException' with message 'Object of class Closure could not be converted to string' in /Users/patricia/Code/thank-views/vendor/laravel/framework/src/Illuminate/Database/Connection.php:390 Stack trace

It seems that it is unable to resolve the id for the user. When I run it in tinker it creates the model with a closure function for those fields. However I want to be able to generate these models to be used for my BusinessTest class. It's unable to resolve these dependencies. I'm not sure whether the best place to resolve these dependencies should be in the ModelFactory or elsewhere in the codebase.

$factory->define(App\Business::class, function (Faker\Generator $faker) {
return [
    'slug' => $faker->word,
    'name' => $faker->name,
    'end_card' => $faker->word,
    'white_label' => $faker->boolean,
    'white_label_url' => $faker->word,
    'payment_header' => $faker->word,
    'payment_amount' => $faker->randomNumber(),
    'payment_amount_display' => $faker->word,
    'payment_cost' => $faker->randomNumber(),
    'payment_activated' => $faker->boolean,
    'main_user_id' => function () {
         return factory(App\User::class)->create()->id;
    },
];});



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

Matching Two Columns Query and Date [Laravel]

I need to search up a person based on their last name and partner last name. I need it to search input on both database columns.

The columns are

$users = Users::where(function($q) use($request) {
                    $q->where('sp1LName', $request->lastName)
                      ->orWhere('sp2LName', $request->lastName);
                  })->where(function($x) use($request){
                      $x->where('sp1LName', $request->partnerLastName)
                        ->orWhere('sp2LName', $request->partnerLastName);
                  })->where('signUpDate', Carbon::parse($request->date)->format('Y-m-d'))
                  ->get();


select * from `users` where (`sp1LName` = ? or `sp2LName` = ?) and (`sp1LName` = ? or `sp2LName` = ?) and `signUpDate` = ? and `users`.`deleted_at

I keep on getting 0 results found when I input this.



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

Laravel 5. Populating a DB. Error "Class does not exist" when execute "seed: db"

I get an error "Class does not exist" when trying to populate my DB by executing
"php artisan seed:db".

UserMoviesSeeder.php in the folder database/seeds has the following content:

<?php

use Illuminate\Database\Seeder;
use App\Project;
use App\UserMovie;
use App\User;

class UserMoviesSeeder extends Seeder
{
    public function run()
    {
      $this->call(ProjectsTableSeeder::class);
    }
}

class ProjectsTableSeeder extends Seeder {

   public function run()
   {
       DB::table('user_movies')->delete();
       DB::disableQueryLog();

       UserMovie::create([
           'user_id' => 1734805,
           'tmdb_id' => 100,
           'ratio' => 4
       ]);

       UserMovie::create([
           'user_id' => 716091,
           'tmdb_id' => 100,
           'ratio' => 4
       ]);
   }
}

I run the command:

php artisan db:seed --class=UserMoviesSeeder

And I get an error:

In Container.php line 752:
Class UserMoviesSeeder does not exist

Why?



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

Laravel 5 Eloquent - adding calculated value as column to collection

I am calculating the distance of a teacher from a school.

I am querying the user table and then the userable_type teacher. The teacher table has the longitude and latitude values.

The following worked for me elsewhere when I query the teacher model directly but not when querying through the user model first!

            $query->whereHas('teacher', function ($query) use ($school) {

                $haversine = "(3961 * acos(cos(radians($school->latitude)) 
                    * cos(radians(latitude)) 
                    * cos(radians(longitude) 
                    - radians($school->longitude)) 
                    + sin(radians($school->latitude)) 
                    * sin(radians(latitude))))";

                $query->select() //pick the columns you want here.
                    ->selectRaw("{$haversine} AS distance")
                    ->whereRaw("{$haversine} < ?", '20');
                    // ->havingRaw('{$haversine}', '<', '20');

            });

The 'distance' field is not created but no errors are thrown! So my question is, in this scenario, how do I add the 'distance' value to each user as I would like to order by the distance?

Thanks, KH...



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

How to decide between PHP with Laravel or Node with Express? [on hold]

Context

My boss gave us a challenge of bringing ideas for development outside client's requests, we called that JgLab. The JgLab main goal is to develop ideas and learning new tecnologies.

We have to create everything. Presentation, app structure, scenarios, implementation and so on...

My idea

I want to build a CRM (Customer Relationship Management) system as an add-on for institutionals website, hotsites and webapps that we sell.

Problem

I want to learning something new as backend developer, but I don't know if I choosing the right tool for the job.

My Experience

  • Worked a very litle with Laravel, more fixing bugs than building the app.
  • I never worked with Node, I'm in process of learning. Learning Node Repo (feel free to create issues and propose good pratices)

I take a look at this question How to decide when to use Node.js? But I'm not satisfied and this question is around 2013, a lot can change in 5 years.

Questions

  • What are the pro and cons for using Laravel/Node in this project?
  • If I still wondering which one should I use, where can I find info?
  • What points should I consider to build this app besides the language/structure?


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

Laravel Eloquent issue with multiple search

I've 2 tables (users, user_data), I'm try to make search with multiple GET method like:

http://xxx.loc/clients?sector_id=1&country_id=1&city_id=2&acc_type=all

if there isn't parameters my code is work.

here is my query code:

$clients = User::whereHas('roles', function ($query) {
        $query->where('name', '=', 'company');
    })->with(['userdata' => function($query) {
        $sector_id      = (isset($_REQUEST['sector_id']) && Input::has('sector_id')) ? Input::get('sector_id') : null;
        $sub_sectors    = (isset($_REQUEST['sub_sectors']) && Input::has('sub_sectors')) ? Input::get('sub_sectors') : null;
        $country_id     = (isset($_REQUEST['country_id']) && Input::has('country_id')) ? Input::get('country_id') : null;
        $city_id        = (isset($_REQUEST['city_id']) && Input::has('city_id')) ? Input::get('city_id') : null;
        $acc_type       = (isset($_REQUEST['acc_type']) && Input::has('acc_type')) ? Input::get('acc_type') : null;



        $conds = [];
        if ($sector_id != null){
            $conds[] = $query->where('sector_id', $sector_id);
        }
        if ($sub_sectors != null){
            $conds[] = $query->whereIn('sub_sectors', $sub_sectors);
        }
        if ($country_id != null){
            $conds[] = $query->where('country_id', $country_id);
        }
        if ($city_id != null){
            $conds[] = $query->where('city_id', $city_id);
        }
        if ($acc_type != null){
            if ($acc_type != 'all'){
                $conds[] = $query->where('acc_type', $acc_type);
            }
        }

        dd($sector_id, $sub_sectors, $country_id, $city_id, $acc_type, $conds);
    }])->paginate(25);

I think my problem with where or orWhere if there are multiple parameters, last test i pushed each not null query to $conds array, but how i can fix my query.

note: all search parameters used in user_data.

Regards,



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

While Registering in Laravel 5.6 I'm getting exception: Exception \ MethodNotAllowedHttpException No message

While Registering in Laravel 5.6 I'm getting exception:

Exception \ MethodNotAllowedHttpException No message

The Controller code is given below:

class ProductController extends Controller
{
    public function insertform()
    {
        return view('clientlayout.main.signup');
    }

    public function insert(Request $request)
    {
        $firstname   = $request->input('firstname');
        $lastname    = $request->input('lastname');
        $companyname = $request->input('companyname');
        $email       = $request->input('email');
        $address1    = $request->input('address1');
        $address2    = $request->input('address2');
        $city        = $request->input('city');
        $state       = $request->input('state');
        $postcode    = $request->input('postcode');
        $country     = $request->input('country');
        $phonenumber = $request->input('phonenumber');
        $password    = $request->input('password');
        $data        = [
            'firstname'   => $firstname,
            'lastname'    => $lastname,
            'city'        => $city,
            'email'       => $email,
            'country'     => $country,
            'address1'    => $address1,
            'address2'    => $address2,
            'state'       => $state,
            'postcode'    => $postcode,
            'password'    => $password,
            'phonenumber' => $phonenumber,
            'companyname' => $companyname,
        ];

        Whmcs::AddClient()->insert($data);

        echo 'Record inserted successfully.<br/>';
        echo '<a href = "/insert">Click Here</a> to go back.';
    }
}

Find below the blade form and suggest me a solution as I'm getting the same error again as : "Method Not Allowed Http Exception"

<form class="container" action="/create" id="needs-validation" novalidate>
    <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); 
?>">
      <div class="row">
        <div class="col-lg-6 col-sm-6 col-12">
           <div class="form-group">
            <label class="text-inverse custom" 
for="validationCustom01">First Name<span class="req">*</span></label>
<input type="text" name="firstname" class="form-control" 
id="validationCustom01"  placeholder="First name"
value="" required maxlength="25" onKeyPress="return ValidateAlpha(event);" 
style="background-color: rgba(19, 35, 47, 0.4); color:#fff;">
            <div class="invalid-feedback">
              Enter Your Firstname
            </div>
          </div>
        </div>
        <div class="col-lg-6 col-sm-6 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="validationCustom02">Last 
Name<span class="req">*</span></label>
            <input type="text" name="lastname" class="form-control" 
id="validationCustom02" placeholder="Last name" value="" required 
maxlength="25" onKeyPress="return ValidateAlpha(event);" style="background- 
color: rgba(19, 35, 47, 0.4); color:#fff;">
            <div class="invalid-feedback">
            Enter Your Lastname
            </div>
          </div>  
        </div>
      </div>
      <div class="row">
        <div class="col-md-6 col-sm-12 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="inputEmail4">Email<span 
class="req">*</span></label>
            <input type="email" name="email" class="form-control" 
id="inputEmail4" placeholder="Email" required maxlength="250" 
style="background-color: rgba(19, 35, 47, 0.4); color:#fff">
            <div class="invalid-feedback">
              Verify Your Email Id
            </div>
          </div>  
        </div>
        <div class="col-lg-6 col-sm-6 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="inputphone">Phone 
 Number<span class="req">*</span>
            </label>
            <input  type="tel" id="phone" name="phonenumber" class="form- 
 control"  placeholder="Phone Number" required onkeypress="return 
 isNumberKey(event)"style="background-color: rgba(19, 35, 47, 0.4); 
 color:#fff">



            <div class="invalid-feedback">
            Enter Correct Mobile Number
            </div>
          </div>  
        </div>

      </div>



      <div class="row">
        <div class="col-md-6 col-sm-12 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="inputEmail4">Address 
1<span class="req">*</span></label>
            <input type="text" name="address1" class="form-control" 
id="inputEmail4" placeholder="Address1" required style="background-color: 
rgba(19, 35, 47, 0.4); color:#fff">
            <div class="invalid-feedback">
             Enter Your Address
            </div>
          </div>  
        </div>
        <div class="col-lg-6 col-sm-6 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="inputpassword">Address 
2</label>
            <input type="text" name="address2" class="form-control" 
id="inputpassword" placeholder="Address2" style="background-color: rgba(19, 
35, 47, 0.4); color:#fff">

          </div>  
        </div>
      </div>
      <div class="row">
        <div class="col-lg-6 col-sm-6 col-12">
          <div class="form-group">
            <label class="text-inverse custom" 
for="validationCustom03">Company Name<span class="req">*</span></label>
            <input type="text" name="companyname" class="form-control" 
id="companyname" placeholder="Company Name" style="background-color: 
rgba(19, 35, 47, 0.4); color:#fff">

          </div>  
        </div>
        <div class="col-lg-6 col-sm-6 col-12">

         <div class="form-group">
            <label class="text-inverse custom" 
for="inputEmail4">Country<span class="req">*</span></label>
            <select name="country" class="custom-select d-block form-control 
countries" id="countryId" required style="background-color: rgba(19, 35, 47, 
0.4); color:#fff">
<option value="">Select Country</option>
</select>
            <div class="invalid-feedback">
             Select Your Country
            </div>
          </div>  

        </div>
      </div>
      <div class="row">
      <div class="col-md-4 col-sm-6 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="select-menu">State<span 
class="req">*</span></label>
            <select name="state" class="custom-select d-block form-control 
states" id="stateId" required style="background-color: rgba(19, 35, 47, 
0.4); color:#fff">
<option value="">Select State</option>
</select>
            <div class="invalid-feedback">
            Select Your State
            </div>
          </div>  
        </div>

        <div class="col-md-4 col-sm-12 col-12">
        <div class="form-group">
            <label class="text-inverse custom" for="select-menu">City<span 
class="req">*</span></label>

            <select name="city" class="custom-select d-block form-control 
cities" id="cityId" required style="background-color: rgba(19, 35, 47, 0.4); 
color:#fff">
<option value="">Select City</option>
</select>
            <div class="invalid-feedback">
            Select Your city
            </div>
          </div>  

        </div>

        <div class="col-md-4 col-sm-12 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="inputEmail4">Zip 
Code<span class="req">*</span></label>
            <input type="text" name="postcode" class="form-control" 
id="inputEmail4" placeholder="Zip Code" required onkeypress="return 
isNumberKey(event)" maxlength="10" style="background-color: rgba(19, 35, 47, 
0.4); color:#fff">
            <div class="invalid-feedback">
             Enter Your Correct Zip Code
            </div>
          </div>  
        </div>
      </div>

       <div class="row">
        <div class="col-md-6 col-sm-12 col-12">
          <div class="form-group">
            <label class="text-inverse custom" 
for="inputpassword">Password<span class="req">*</span></label>
            <input type="password" name="password" class="form-control" 
name="password" id="password" placeholder="Password" required="required" 
style="background-color: rgba(19, 35, 47, 0.4); color:#fff">
           <!-- <div class="invalid-feedback">
             Enter Your Password
            </div>-->

          </div>  
        </div>
        <div class="col-md-6 col-sm-12 col-12">
          <div class="form-group">
            <label class="text-inverse custom" for="inputpassword">Confirm 
Password<span class="req">*</span></label>
            <input type="password" name="password" class="form-control" 
id="confirmpassword" placeholder="Confirm Password" required="required" 
style="background-color: rgba(19, 35, 47, 0.4); color:#fff">
           <!-- <div class="invalid-feedback">
             Enter Your Confirm Password
            </div>-->
          </div>  
        </div>
      </div>

      <div class="row">

        <div class="col-lg-12 col-sm-6 col-12">
          <div class="form-group">
            <label class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input"  
id="inputpassword" required>

              <span class="custom-control-indicator"></span>
              <span class="custom-control-description custom"><a 
href="Terms_Service">I have read and agree to Terms and Conditions</a> 
</span>
            </label>
          </div>  
        </div>
      </div>

      <div class="row">
        <div class="col-lg-12 col-sm-12 col-12 text-center" style="padding- 
bottom: 20px;">
            <button class="btn btn-info" type="submit">Submit form</button>
        </div>
      </div>  
    </form>

Find the coding of my controller form, blade form, view and route form and give me a solution to solve this "Method not allowed Http Exception".



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

Load different methods depending on which view is being browsed LARAVEL

Trying to load different views and methods depending on which view the user is browsing.

Views:

public function edit()
{    
    if("SOMETHING")return View::make('store_edit');
    If("SOMETHING")return View::make('product_edit');
}

Methods:

public function destroy($id)
{
    if(SOMETHING){
       $store = Store::find($id);
       $store->delete();
       return redirect('/store');
     }
    if(SOMETHING){
       $product = Product::find($id);
       $product->delete();
       return redirect('/product');
      }
}

What can be used in the if() statements depending on which view is browsed in order to delete the right item and not having to rewrite the functions for each table.



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

Laravel 5.5 - Notifications/Subnotifications for 1 million followers?

I use a notifications table and a subnotifications table, and I am also using queues so it runs in the background when a user posts something. When a user has 10 followers and they create a post, the notifications table gets a single entry which includes the post data for the notification, and the subnotifications table gets 10 entries (one subnotification per follower, each referring to the id of the notification, so we don't have to repeat the notification data 10 times, with a read_at to know if it was read or not by that follower).

This is quick and works great without any issues. However, when testing with 1 million followers, it takes about ~6 hours to insert the subnotifications for one post! This of course is not acceptable, as it is takes too long to insert 1 million subnotifications, one per follower. Imagine that same user posts 10 posts, that'll be like ~60 hours of inserting and 10 million subnotification rows.

I just want followers to know there is a new post if they didn't read it yet. Is there a better, more efficient way that scales?



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

"artisan make:controller" not creating controller in folder

I am creating controller in laravel inside one folder called Admin but it just creating AdminAdminContoller, uisng this commmand

artisan make:controller Admin\AdminController --resource

To to create folder Admin and then AdminController inside that folder ?



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

Laravel 5.4 Auth::check() returning false

I am using laravel 5.4 as bankend for my application, And for front-end i am using angular. I am using laravel auth for authentication, Issue is Auth::attempt() is working fine and if immediately i print the Auth::user() then it will print the data but it return false if i try to fecth it in next method, But this functionality is is working fine in hosted server.

Tested,

  1. Changed session from file to database.
  2. Changes in kernel.php (Content of $middleware).
  3. Did php artisan make:auth one more time.
  4. Did changes in user table column.
  5. Added private $primarykey = 'id' to model.
  6. Added 'web' middleware to all routes.

This is my Controller

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;

public function login()
{
 if (Auth::attempt(['email' => $email, 'password' => $password , 
  'status' => $status])) 
        {
            $response = array('response' =>'Succssfully Login!' , 'success' => true);

            return $response;
        }
 }

This is where i am using Auth::check()

public function check() 
{
    if(Auth::check())
        $response = array('response' =>'Authenticated' , 'success'=>true);
    else
        $response = array('response' =>'UnAuthenticated' , 'success'=>false);

    return $response;    
}

I am confuesd because same code is woking fine in hosted server but not wokking in local, Do i need to do any http realated cahnges in laravel for this ?.

Thank you.



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

conditional relationship for "with()"

I have a table called transactions and another table called cars with the below structure:

transactions

| id  | date | amount | status | user_added |
| --- | ---- | ------ | ------ | ---------- |

cars

| id  | plate | specs | buy_transaction  | sell_transaction  |
| --- | ----- | ----- | ---------------- | ----------------- |

A car has always a buy_transaction but not always a sell_transaction, situation is that I am trying to get all transactions (that might be car-related or not car-related) and include the CAR related to that transaction weather it is sold or bought, so I need to make the relationship conditional but i couldn't achieve that.

$journal = Transaction::with(
    ['user'=> function($query) { 
        $query->select('id', 'name');
     },
     'income',
     'outcome'
     'car'
    ])->where('date', '>=', $fromDate)->where('date', '<=', $toDate);

This is the modal class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{

    public function income()
    {
        //.....
    }

    public function outcome()
    {
        //.....
    }

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

    // *** problem starts here ***

    public function car()
    {
        if (transaction status == 1) {

        return $this->belongsTo('App\Car', 'id', 'sell_transaction');

        }
        else if (transaction status == 2) {

        return $this->belongsTo('App\Car', 'id', 'buy_transaction');

        }
    }

}

I need to stick to that query structure because the query command is longer and I am joining and including other tables, I was hoping I could make the car() belongsTo relation conditional somehow.

I followed some similar situations like this but it didn't work for me.

Thank you.



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

Download Big Protected Files from api! Laravel

I Used download function for download a file in the protected storage folder but when I requested to the server for response a 50 MB file, first the server download it on browser then send it to the user. in other words, I want to user download a file after send request to laravel api! Backend: Laravel Frontend: Angular 4 thanks.

I used these code

$headers = ['Content-Type' => $file->mime,
'Content-Disposition'=>'attachment; filename="' . $file->original_name . 
'"','Access-Control-Expose-Headers' => 'Content-Disposition'];

return response()
    ->download(storage_path("app/{$file->path}"),$file->original_name, 
    $headers);

and it works fine but my problem is when I serving request to download a file with 50 MB size, response time is very long because first, 50 MB files load on browser network tab and nothing show to the user to know about download file.



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

Save a File To mysql Database From a form using laravel

Good day Everyone, I'm less than 1 week old in laravel. I'm trying to save a Register CV page to MySQL database. Although my Form contains an upload file. While saving it to the database only the name of the file is saved the file itself isnt there. My code goes thus. RegisterController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\candidate;

use App\Http\Requests;

class RegisterController extends Controller
{
    public function register(Request $request) {
        $this->validate($request, [
            'surname' => 'required',
            'other_name' => 'required',
            'email' => 'required',
            'phone' => 'required', 
            'gender' => 'required',
            'field' => 'required',
            'qualification' => 'required',
            'resume' => 'required'
        ]);

        $candidates = new Candidate;
        $candidates->surname = $request->input('surname');
        $candidates->other_name = $request->input('other_name');
        $candidates->email = $request->input('email');
        $candidates->phone = $request->input('phone');
        $candidates->gender = $request->input('gender');
        $candidates->field = $request->input('field');
        $candidates->qualification = $request->input('qualification');
        
        $candidates->resume = $request->input('resume');
        $candidates->save();
        return redirect('/career')->with('response', 'Registered Successfully');
    }
}

2018_03_28_152114_create_candidates_table.php

<?php

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

class CreateCandidatesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('candidates', function (Blueprint $table) {
            $table->increments('id');
            $table->string('surname');
            $table->string('other_name');
            $table->string('email');
            $table->string('phone');
            $table->string('gender');
            $table->string('field');
            $table->string('qualification');
            $table->string('resume');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('candidates');
    }
}
then the form
<form class="form-horizontal pv-20" action="/career/test-apply" method="POST" role="form">
            <input type="hidden" name="_token" value="">

          .........
          ........
               

                <div class="form-group">
                    <label class="col-sm-2" for="resume">Upload Resume</label>
                    <div class="col-sm-10">
                        <input class="form-control" type="file" name="resume" id="resume"         accept="application/pdf">                  
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-6" for="resume"></label>
                    <div class="col-sm-6">
                        <button type="submit" class="btn btn-default btn-curve btn-animated pull-right">Submit <i class="fa fa-play"></i></button>                  
                    </div>
                </div>
            </form>


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

Laravel DigitalOcean - Call to undefined method Buzz\Browser::addListener()

I'm new to the DigitalOcean API and I'm trying some stuff out to see how it works in laravel. I'm trying to get account information by using their documentation. In their documentation it says the following:

// create an adapter with your access token which can be
// generated at https://cloud.digitalocean.com/settings/applications
$adapter = new BuzzAdapter('your_access_token');

// create a digital ocean object with the previous adapter
$digitalocean = new DigitalOceanV2($adapter);

Now when I want to grab the user's account information I have to this:

$account = $digitalocean->account();

When it works I should receive the account information when I Dump and Die $account but instead I receive an error stating:

Call to undefined method Buzz\Browser::addListener()

What is causing this?

Thanks in advance!



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

I got a json data from whmcs using whmcs api. how to decode the json data and print the data in laravel view template

Find the json data from whmcs API and suggest me a solution to display the mentioned data as I'm getting error as "Trying to non-object and json_decode() expects parameter 1 to be string".

"products": {
"product": [
  {
    "pid": "1",
    "gid": "1",
    "type": "hostingaccount",
    "name": "super lite",
    "description": "1 website",
    "module": "cpanel",
    "paytype": "recurring",
    "pricing": {
      "INR": {
        "prefix": "\u20b9",
        "suffix": "INR",
        "msetupfee": "0.00",
        "qsetupfee": "0.00",
        "ssetupfee": "0.00",
        "asetupfee": "0.00",
        "bsetupfee": "0.00",
        "tsetupfee": "0.00",
        "monthly": "-1.00",
        "quarterly": "-1.00",
        "semiannually": "-1.00",
        "annually": "1668.00",
        "biennially": "3096.00",
        "triennially": "3924.00"
      }

This is my controller code

class GetProductController extends Controller
{
public function show(){

    $products = Whmcs::GetProducts([
        'pid',
        'name',
        'price',
        'description'
   ]);

    $products = json_decode($products, true);

        return view('main.SME_Hosting',compact('products'));

    // return view('main.SME_Hosting',['products'=>$products]);

    }

This is my view code

 @foreach ($products as $product)
                        


@endforeach



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

mercredi 28 mars 2018

Dusk not working with factories and/or migrations in Homestead

Using a fresh install of Laravel and dusk, then copying the exact test from the docs for logging in the user, I get an error that the users table doesn't exist.

I don't get any error when using a factory to create a user, but when trying to login as that user, i can see the browser window opening (screenshoots), typing in the creds, then seeing the error that user can't be found.

I see that Dusk tests never ran the migrations.

I change my config/database.php and .env.dusk.local

// config/database.php

'connections' => [
         'testing' => [
         'driver' => 'sqlite',
         'database' => database_path('testing.sqlite'),
         'prefix' => '',
          ],
],

`// .env.dusk.local

    APP_URL=http://project.dev
    APP_ENV=testing
    DB_CONNECTION=testing`

and ran composer update but the error persist :(



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

Laravel and 3+ table pivot

I'm trying to wrap laravel around a relatively basic structure - users with roles in multiple organisations, as in a single user can have many roles in many organisations. This allows a user to have a single set of sign-in credentials with different access depending on the organisation they're acting behalf of.

In MySQL/MariaDB, i would typically represent this with a table having three columns with a unique combination constraint

CREATE TABLE `organisation_role_user` (
  `organisation_id` int(10) unsigned NOT NULL,
  `role_id` int(10) unsigned NOT NULL,
  `user_id` int(10) unsigned NOT NULL,
  UNIQUE KEY `organisation_role_user` 
(`organisation_id`,`role_id`,`user_id`),
  KEY `organisation_role_user_ibfk_2` (`user_id`),
  KEY `organisation_role_user_ibfk_3` (`role_id`),
  CONSTRAINT `organisation_role_user_ibfk_1` FOREIGN KEY 
(`organisation_id`) REFERENCES `organisations` (`id`) ON DELETE CASCADE,
  CONSTRAINT `organisation_role_user_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `organisation_role_user_ibfk_3` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
)

I'm wondering that someone must have used a similar construct in Laravel / Eloquent before me - it's a basic thing.

Is there a way to do this neatly with attach() / detach() / sync() working? There must be something i'm missing?

Thank you for your time.



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

Hardcoding email into Mailable Laravel

I have a members website and I need to send out 2 email upon user registration.

  1. Welcome email to new user (This is fine)
  2. Notice email to admin notifying them of the new user.(Need Help)

I'm using Events and Listeners to do this. I can currently send both emails to the new registered user so I believe my issue is with the Mail::to function

Here is what is currently working, but it's sending to the new registered user.

I need it to go to admin@mysite.com. How can I hardcode in that email, or grab the user with admin privileges from my users table?

Could I do something like this:

Mail::to($event->user->username('admin')->email)->send(new NewUserCreated($event->user));

The above gives me an error: Call to undefined method Illuminate\Database\Query\Builder::username()

Listener: SendNewUserCreated.php

public function handle(NewUser $event)
{
    Mail::to($event->user->email)->send(new NewUserCreated($event->user));
}

Mail: NewUserCreated.php

public function build()
{
    return $this->subject('Custom Subject Here')->markdown('emails.staff.newusercreated');
}

Mail Blade: newusercreated.blade.php

@component('mail::message')
# A new user has registered on Website.

Please check that the following credentials match your records.

@component('mail::panel')
- **User Name:** 
- **Full Name:**  
- **Email:** 
- **4 Digit Pin:** 
- **Street:** 
- **City:** 
- **State:** 
- **Zip:** 
@endcomponent

@component('mail::button', ['url' => 'http://wesite.oo/admin'])
Grant Access
@endcomponent


Thank You,<br>
*, Notifier*
@endcomponent



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

Fresh Laravel install deletes server.php on artisan serve

I'm a bit fresh to Laravel. I installed it via composer in the xampp/htdocs file. I installed the latest version 5.6. The install works with no errors, and the file structure is as it should be.

When I run the php artisan serve command from inside the folder, it deletes the server.php file and therefore outputs the error:

This site can’t be reached

localhost refused to connect.

So I thought why not just add a new file inside and it will work... Well i suddenly do not have permissions to add files to this folder.

I tried a new install a few times, but the situation is always the same.

Has anybody else encountered this problem?



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

Can we add image in categories in highcharts?

I have a highchart in which I am displaying my data, I wanted to show the images in place of the text in categories? Is it possible to replace image with text on categories? I am fetching categories dynamically.



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