dimanche 31 mars 2019

I want to get 2 functions by 1 route to view

I want to get 2 functions by 1 route to view

I tried like this but not working

Route::post('prospect', ['ProspectController@store' , 
                         'course_controller@show_details']);



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

Why kategori filter must be chosen for filtering working?

I make conditional filtering using ajax in laravel 5. The filtering is working fine only when the 'kategori' field is selected.

I am using request in if statement for filtering:

  $query = DB::table('itemregistrations')
    ->join('sections', 'itemregistrations.SectionID', '=', 'sections.SectionID')
    ->join('categories', 'itemregistrations.CategoryID', '=', 'categories.CategoryID')
    ->join('operasi', 'itemregistrations.OperasiID', '=', 'operasi.OperasiID')
    ->select('itemregistrations.name', 'itemregistrations.SectionID', 'itemregistrations.CategoryID', 'itemregistrations.OperasiID', 'itemregistrations.BangsaID', 'itemregistrations.statusProID', 'sections.sectionname', 'categories.categoryname', 'operasi.operasiname', 'itemregistrations.Nobadan', 'itemregistrations.ItemRegistrationID');

    // if(request()->has('section')) {
    if($request->input('section') != ''){
        $query->where('itemregistrations.SectionID', $request->input('section'));
    }

    if($request->input('statuspro') != '') {
        $query->where('itemregistrations.statusProID', $request->input('statuspro'));
    }


    if($request->input('bangsa') != '') {
        $query->where('itemregistrations.BangsaID', $request->input('bangsa'));
    }

    if($request->input('agama') != '') {
        $query->where('itemregistrations.AgamaID', $request->input('agama'));
    }

    if($request->input('jantina') != '') {
        $query->where('itemregistrations.JantinaID', $request->input('jantina'));
    }

    if($request->input('negeri') != '') {
        $query->where('itemregistrations.NegeriID', $request->input('negeri'));
    }

    if($request->input('status_kahwin') != '') {
        $query->where('itemregistrations.KahwinID', $request->input('status_kahwin'));
    }

    if($request->input('kategori') != '') {
        $query->where('itemregistrations.CategoryID', $request->input('kategori'));
    }

    if($request->input('pangkat') != '') {
        $query->where('itemregistrations.OperasiID', $request->input('pangkat'));
    }
    $newitem = $query->get();

    return response::json($newitem);

This is the html code for the selection fields:

   <div class="form-group">
            <div class="row">
              <div class="col-lg-2"> 
                
              </div>
              <div class="col-lg-2"> 
                
              </div>
            </div>
          </div>
        <!-- Carian mengikut status -->
          <div class="form-group">
              <div class="row">
                .....like so........

                </div>
              </div>
          </div>
        <!-- Carian mengikut kategori dan pangkat -->
          <div class="form-group">
            <div class="row">
                <div class="col-lg-2">
                  <label for="kategori">Kategori:</label>
                </div>
                <div class="col-lg-3"> 
                  <select name="kategori" id="kategori" class="form-control select2" style="width:250px">
                      <option value="">-- pilih --</option>
                      @foreach ($categories as $key => $value)
                      <option value=""></option>
                      @endforeach
                  </select>
                </div>
            </div>
          </div>

          <div class="form-group">
              <div class="row">
                <div class="col-lg-2">
                  <label for="pang">Pangkat:</label>
                </div>
                <div class="col-lg-6"> 
                  <select name="pangkat" id="pangkat" class="form-control select2"style="width:500px">
                  <option>-- pilih --</option>
                  </select>
                </div>
              </div>
          </div>
          <!-- Carian mengikut bangsa -->
          <div class="form-group">
              <div class="row">
                <div class="col-lg-2"> 
                  
                </div>
                .....like so.....
              </div>
          </div>
          <!-- Carian mengikut agama -->
          <div class="form-group">
              <div class="row">
                <div class="col-lg-2"> 
                  
                </div>
                ....like so.....
              </div>
          </div>
          <!-- Carian mengikut jantina -->
          <div class="form-group">
              <div class="row">
                <div class="col-lg-2"> 
                  
                </div>
                ....like so....
              </div>
          </div>
          <!-- Carian mengikut negeri lahir -->
          <div class="form-group">
              <div class="row">
                <div class="col-lg-2"> 
                  
                </div>
                ....like so.....
              </div>
          </div>
          <!-- Carian mengikut status perkahwinan -->
          <div class="form-group">
              <div class="row">
                <div class="col-lg-2"> 
                  
                </div>
                ...like so...
              </div>
          </div>

Ajax call script to get the data:

<script type="text/javascript">
      $( "#cari" ).click(function() {
        // alert($('#kategori').val());
        var seksyen = $("#section").val();
        var status_pro= $("#statuspro").val();
        var kategori_id= $("#kategori").val();
        var pangkat_id= $("#pangkat").val();
        var bangsa_id= $("#bangsa").val();
        var agama_id= $("#agama").val();
        var jantina_id= $("#jantina").val();
        var negeri_id= $("#negeri").val();
        var kahwin_id= $("#status_kahwin").val();
         $.ajax({
            url: '?'+ $.param({'section': seksyen,'statuspro': status_pro,'bangsa': bangsa_id,'agama': agama_id,'jantina': jantina_id,'negeri': negeri_id,'status_kahwin': kahwin_id,'kategori': kategori_id,'pangkat': pangkat_id}),
            dataType: 'json',
            success: function (data) {
                console.log(data);
                $('#datatable tr').not(':first').remove();
                var html = '';
                for(var i = 0; i < data.length; i++){
                    html += '<tr>'+
                                '<td>' + data[i].name + '</td>' +
                                '<td>' + data[i].sectionname + '</td>' +
                                '<td>' + data[i].categoryname + '</td>' +
                                '<td>' + data[i].operasiname + '</td>' +
                                '<td>' + data[i].Nobadan + '</td>' +
                                '<td class="text-center">' + '<a href="/'+ data[i].ItemRegistrationID +'">' + '<i class="fa fa-folder fa-fw" rel="tooltip" title="view profil">'+'</i>'+'</a>' + '</td>' +
                            '</tr>';
                    }   
                $('#datatable tr').first().after(html);
            },
            error: function (data) {
            }
        });
      });
  </script>

Why the filtering not working if the kategori field is not selected? There is no error in console log but it doesn't have any data in the array result.



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

variable is not working dynamically with email id

i am trying to send email to different users at a time. email is sending to the users but name is not working dynamically. name of the first user is sending to all users. here is my code:

 foreach ($entertainers as $accept) {

 $entertain = Entertainer::where('mail_soushin',$accept)->first();
 $entertainer= $entertain->name;      

 $this->view('mail.mail101',compact('entertainer','event','user'))->to($accept)->from($admin->mail_soushin,'Dream Master')->subject('【ドリームマスターズ】コンペ募集が開始されました');
 $entertainer = null;

           }

this is blade code to show the name of user

<span></span>

here $entertainers is array of emails and $entertainer is the name of a particular user. but this $entertainer variable is not dynamically updated based on email.



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

Cannot configure Laravel API on a subdirectory via .htaccess

I have the following dummy local website (configured through two different virtual hosts):

[vhost 1] https://www.test-laravel.com

DocumentRoot "${INSTALL_DIR}/www/[WEBSITE-DIR]"

[vhost 2] https://www.test-laravel-direct.com

DocumentRoot "${INSTALL_DIR}/www/[WEBSITE-DIR]/laravel/public"

You can check it out here through GitHub:

https://github.com/napolev/test-laravel.com

Inside its directory I dropped 4 files:

index.php
page_01.php
page_02.php
page_03.php

with the same content (just to indicate the current file):

<?
echo 'You are on: '.$_SERVER['PHP_SELF'];
?>

Also, inside its directory I installed Laravel with:

$ laravel new api

On file: laravel\routes\api.php I configured the following route:

Route::post('/echo-post', function (Request $request) {
    return request()->all();
});

If I use [vhost 2] with Postman, using the following POST URL request:
(this case the domain is pointing to the subdirectory: /laravel/public instead the root directory)

https://www.test-laravel-direct.com/api/echo-post?param1=value1&param2=value2&param3=value3

I get the expected response:

{
    "param1": "value1",
    "param2": "value2",
    "param3": "value3"
}

Then, I want to use [vhost 1] with Postman, using the following POST URL request:
(this case the domain is pointing to the root directory instead the subdirectory: /laravel/public)

https://www.test-laravel.com/api/echo-post?param1=value1&param2=value2&param3=value3

For that I configured the root .htaccess file like:

RewriteEngine On
RewriteBase /laravel/

RewriteRule ^api/(.*)$ /api/$1 [L]

But when running the request with Postman I get the following output:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
    <head>
        <title>500 Internal Server Error</title>
    </head>
    <body>
        <h1>Internal Server Error</h1>
        <p>The server encountered an internal error or
misconfiguration and was unable to complete
your request.</p>
        <p>Please contact the server administrator at 
 admin@example.com to inform them of the time this error occurred,
 and the actions you performed just before this error.</p>
        <p>More information about this error may be available
in the server error log.</p>
    </body>
</html>

On the Apache error log I get the following:

AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

Do you have any idea on how can I use [vhost 1] with the following POST URL request?

https://www.test-laravel.com/api/echo-post?param1=value1&param2=value2&param3=value3

Thanks!



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

How to paginate the results from ajax call?

I had queried data using ajax in Laravel 5.

This is the code to display the result:

  <script type="text/javascript">
      $( "#cari" ).click(function() {
        // alert($('#kategori').val());
        var seksyen = $("#section").val();
        var status_pro= $("#statuspro").val();
        var kategori_id= $("#kategori").val();
        var pangkat_id= $("#pangkat").val();
        var bangsa_id= $("#bangsa").val();
        var agama_id= $("#agama").val();
        var jantina_id= $("#jantina").val();
        var negeri_id= $("#negeri").val();
        var kahwin_id= $("#status_kahwin").val();
         $.ajax({
            url: '?'+ $.param({'section': seksyen,'statuspro': status_pro,'bangsa': bangsa_id,'agama': agama_id,'jantina': jantina_id,'negeri': negeri_id,'status_kahwin': kahwin_id,'kategori': kategori_id,'pangkat': pangkat_id}),
            dataType: 'json',
            success: function (data) {
                console.log(data);
                $('#datatable tr').not(':first').remove();
                var html = '';
                for(var i = 0; i < data.length; i++){
                    html += '<tr>'+
                                '<td>' + data[i].name + '</td>' +
                                '<td>' + data[i].sectionname + '</td>' +
                                '<td>' + data[i].categoryname + '</td>' +
                                '<td>' + data[i].operasiname + '</td>' +
                                '<td>' + data[i].Nobadan + '</td>' +
                                '<td class="text-center">' + '<a href="/'+ data[i].ItemRegistrationID +'">' + '<i class="fa fa-folder fa-fw" rel="tooltip" title="view profil">'+'</i>'+'</a>' + '</td>' +
                            '</tr>';
                    }   
                $('#datatable tr').first().after(html);
            },
            error: function (data) {
            }
        });
      });
  </script>

The code for the table is as follows:

 <table class="table table-striped table-bordered" id="datatable" >
         <tr>
            <th>Nama</th>
            <th>Seksyen</th>
            <th>Kategori</th>
            <th>Pangkat</th>
            <th>No Personal</th>
            <th>Action</th>
         </tr>
</table>

But the results will display a long list of names. How to modify the codes to paginate the results displayed?



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

How to set select option to default value without refreshing the page

I'm trying to set the values for select options to default value whenever I changed report options without submitting or refreshing the page.

But whenever I changed reports, the values for session and semester remains the same and will only change back to default value if I submit the report or refresh the page.

The HTML/Laravel

<div class="form-group">
    <label class="control-label col-md-offset-1 col-md-2">Report:</label>
        <div class="col-md-6">
            <select id="list-report" name="list_report" class="form-control" required>
                <option></option>
            </select>
        </div>
</div>
<div id="div-ses" class="form-group group-filter" style="display: none;">
    <label class="control-label col-md-offset-1 col-md-2">Session:</label>
        <div class="col-md-6">
            <select id="list-session" name="list_session" class="form-control" style="width: 100%;">
                <option value=""></option>
            @foreach($list_session as $session)
                <option value=""></option>
            @endforeach
            </select>
        </div>
</div>
        <div id="div-sem" class="form-group group-filter" style="display: none;">
    <label class="control-label col-md-offset-1 col-md-2">Semester:</label>
        <div class="col-md-6">
            <select id="list-semester" name="list_semester" class="form-control" style="width: 100%;">
                <option value=""></option>
            @foreach($list_semester as $semester)
                <option value=""></option>
            @endforeach
            </select>
        </div>
</div>


The JQuery

$(document).ready(function() {

var list_report = <?php echo $json_list_report; ?>;


$('#list-report').select2({
    data: list_report,
    allowClear: true,
    placeholder: 'Please Select Report Name'
});
$('#list-session').select2({
    placeholder: 'Please Select Session',
});
$('#list-semester').select2({
    placeholder: 'Please Select Semester',
});


$('#list-report').on('keyup change', function() {
    $('#list-session').prop('selectedIndex', 0);
    $('#list-semester').prop('selectedIndex', 0);
});


});

As you can see, the 'keyup change' is supposed to set the value of select back to default value but it does not seem to work. I suspect this is laravel's logic error but I don't know how to fix this. Any help?

I expect the value for session and semester dropdown would be "Please Select Session/Semester" but the actual output is the value itself e.g Session: 2018/2019, Semester: 2



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

Larave 5 Server Error 500 Hosting in cpanel

I have already uploaded my laravel project folder into cpanel hosting. I have followed many examples here but still getting the famous 500 internal error. This is what I have done:

I has separated public folder in my laravel project and put in my public_html folder. I have made the rest of my laravel project into myapp folder.

Into my public_html folder, I have changed this lines:

require __DIR__.'/../myapp/vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../myapp/bootstrap/app.php';

This is my .env file:

APP_NAME=Driveostle
APP_ENV=local
APP_KEY=base64:xxx
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://www.driveostle.ma

This is my .htaccess file:

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

    RewriteEngine On

    # 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
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>


This is my server.php file:

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylor@laravel.com>
 */

$uri = urldecode(
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
    return false;
}

require_once __DIR__.'/public/index.php';

I still got the HTTP ERROR 500 after typing my domaine name.

After searching here, I have found someone that asked for editing the .htaccess by adding this code:

<IfModule mod_rewrite.c>
   RewriteEngine On 
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

The error that I obtained was different:

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at webmaster@driveostle.ma to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

Also, my PHP Selector version in Cpanel, I have choose the 7.1 version.

And in my composer.json file:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "intervention/image": "^2.4",
        "laravel/framework": "5.5.*",
        "laravel/tinker": "~1.0",
        "mews/purifier": "^2.0"
    },
...

I don't know what is missed in my configuration, It is my first time hosting a laravel website, I hope the elements that I have posted will give you an idea of what I have missed.

If you need any file content, I will post it with pleasure.

Thank you



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

Laravel whereHas getting the relationship

I'm doing a Laravel application to manage events. An Attendant and and Event have a belongsToMany relationship. An attendant has multiple events and viceversa. The pivot column has an extra field called uuid, this is like the ticket id to the event. I need to validate the entrance of an Attendant to an Event. So the Attendant scans a QR code with the uuid of the pivot table.

So I have this function

public function validateTicket(Request $request, $ticket) {
    $event = Event::fromTicket($ticket);
    \Log::info($event);
    return new EventResource($event);
}

And the static method fromTicket is:

public static function fromTicket($ticket) {
    return static::whereHas('attendants', function($q) use ($ticket) {
        $q->where('uuid', $ticket);
    })->first();
}

The problem is that I need the relationship too, this because I need to register the hour of entrance of an Attendant, and this entrance could happen many times.

Is there a way to return the relationship too during the whereHas query?

Thanks in advance.



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

How to say browser to start download file?

Using client side I do POST request to Laravel to get back file to browser:

$headers = [
             'Content-Type' => 'application/vnd.ms-excel',
             'Content-Disposition' => "attachment; filename='Report.xls'"
        ];

        return response()->download(storage_path('app/'.$path.$filename), $filename, $headers);

It returns me binary file in response:

enter image description here

Response headers are:

enter image description here



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

How to send Single Input Field value to Controller with JQuery in Laravel

I want to send a single input form value to Database with JQuery in Laravel.

Here is the Input Field :

     <input type="text" id="comment">

     <button id="cmntSubmit" type="button">Post</button>

Here is my jquery code:

  $(document).on("click","#cmntSubmit",function(){
      var cmnt = $("#comment").val();

  $.ajax({
      url: "",
      data: cmnt,
      success: success,
      dataType: dataType
          });

How will I send this comment field with JQuerry to my Laravel Controller and receive the comment field value with $request ?



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

I created 2 functions to same view in same controller but last route's function only working

I created 2 functions to same view in same controller but last one only working

This is my function

class ProspectController extends Controller {

    public function get_prospects() {
        $prospects = DB::select('select * from prospect');
        return view('prospect', ['prospects' => $prospects]);
    }

    public function get_courses() {
        $courses = DB::select('select * from course');
        return view('prospect', ['courses' => $courses]);
    }

}

This is my route

Route::get('prospect', 'ProspectController@get_courses');
Route::get('prospect', 'ProspectController@get_prospects');

This is my view file

@foreach($courses as $course)

      <input type="checkbox" id="" 
      name="course_intrested[]" value="">
      <label for="defaultCheck"></label>

@endforeach

But i'm getting this error

 Undefined variable:
 courses (View:C:\xampp\htdocs\laravel\customer_inquiry_model\resources\
 views\prospect.blade.php)

But course function working when I change route like this

 Route::get('prospect', 'ProspectController@get_prospects');
 Route::get('prospect', 'ProspectController@get_courses');

but first one is not working. This is my problem.....



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

Unable to add foreign key to DB table

I am trying to add a foreign key constraint into my questions table but when I run php artisan migrate I get the following error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table questions add constraint questions_best_answer_id_foreign foreign key (best_answer_id) references answers (id) on delete SET NULL)

Up and down methods in my "add_foreign_best_answer_id_to_questions_table.php"

public function up()
    {
        Schema::table('questions', function (Blueprint $table) {
            //Define the foreign key
            $table->foreign('best_answer_id')
                  ->references('id')
                  ->on('answers')
                  ->onDelete('SET NULL');
        });
    }

    public function down()
    {
        Schema::table('questions', function (Blueprint $table) {
            $table->dropForeign(['best_answer_id']);
        });
    }
}

My Answer Model

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

        static::created(function ($answer){
            $answer->question->increment('answers_count');
        });

        static::deleted(function($answer){
            $answer->question->decrement('answers_count');
        });
    }


I am trying to migrate to the DB to create a FK on the answers table but I get the error above.

Are there errors in my code?

Thank you!



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

Laravel 5.8: Get Session id from DataSet

I made a table which lists all the sessions of a specific user. I want to be able to delete a session from a button I created which should point to the delete route (/sessions/ID_STRING).

Table

@foreach($sessions as $session){
   <tr>
      <td><i data-sessionId=''></td>
   </tr>
@endforeach

The rest is done via JS, however, this doesn't work. After minutes of debugging, I found out that $session->id returns 0 instead of the real id. I set a breakpoint right after the line where I'm getting my sessions and took a look at the array.

$sessions = Session::whereUserId($user->id)->get();

Inside my debugging window I tried a few things and the result surprised me:

$sessions[0]->getAttributes()["id"]; //returns correct id
$sessions[0]->id; //returns 0
$sessions; //searching for "attributes" shows the correct id too

Why does it return 0 when accessing it via the magic method and how can I fix this? The table is rendered via JS so I can't use my workaround with ->getAttributes()

Sessions.php

class Session extends Model
{
    public $timestamps = false;

    protected $hidden = [];
}



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

Appending Query String with multiple filters

I have a filter bar that searches one filter at a time, however I would like for it to select multiple filters at once, my links for the filters all currently have a single query string, but is there a way to append the query string with another query?

Currently I set up my filters like so in the code below in my Controller

$products = new Product;


        $queries = [];

        $columns = [
            'beertype_id', 'packaging', 'brewery_id'
        ];

        foreach ($columns as $column){
            if (request()->has($column)){

            $products = $products->where($column, request($column));

                $queries[$column] = request($column);
        }


        }

        $products = $products->paginate(10)->appends($queries);

And then call them in the blade template like so

<p>Filter Products:</p>

       <a href="/products">Reset</a>

        <ul>
            <p>Types of Beer:</p>

            <li class="filter-link"><a href="/products?beertype_id=1" >IPA</a></li>
            <li class="filter-link"><a href="/products?beertype_id=2">Lager</a></li>
            <li class="filter-link"><a href="/products?beertype_id=3">Pale Ale</a></li>
        </ul>

         <ul>
            <p>Packaging:</p>
             <li class="filter-link"><a href="/products?packaging=bottle">Bottle</a></li>
             <li class="filter-link"><a href="/products?packaging=can">Can</a></li>
             <li class="filter-link"><a href="/products?packaging=keg">Keg</a></li>
         </ul>

         <ul>
             <p>Brewery:</p>

             <li class="filter-link"><a href="/products?brewery_id=2">Kinnegar</a></li>
             <li class="filter-link"><a href="/products?brewery_id=3">White Hag</a></li>
             <li class="filter-link"><a href="/products?brewery_id=4">Quilmes</a></li>

         </ul>

What I would like to do is end up with a query string like ?beertype_id=3&beertype_id=5&brewery_id=2 etc, how could I do this? Any help would be greatly appreciated!



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

How to make Eloquent query for Group by, with HAVING and MAX

I have SQL query which I need to convert to Eloquent and no idea where to write MAX conditions. How it is posible to convert it without much Raw sql? Thank you!

SELECT bike_id
FROM bike_filters
GROUP BY bike_id
HAVING
   MAX(bike_category_id in (416,11111)) = 1
   AND MAX(bike_category_id in (5555,779)) = 1
   AND MAX(bike_category_id in (5555,772)) = 1

Table Structure:

| id | bike_id | bike_category_id |
| 1  | 3       | 416              |
| 2  | 3       | 779              |
| 3  | 3       | 344              |
| 4  | 3       | 332              |
| 5  | 4       | 444              |
| 5  | 5       | 555              |

The purpose of this query is to get bike_ids, which has all parameters by the query - bike can have 20 filters, but if user searches by 5 and bike matches them, we get bike_id by this query.



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

Selecting multiple filters using Query Strings Laravel

Currently I have a filter bar that works, but it only selects one filter at a time, how could I get it to select multiple filters at once by simply adding on to the current query string?

This is what I have in my Controller

class ProductController extends Controller
{
    public function index()
    {

        $products = new Product;

        $queries = [];

        $columns = [
            'beertype_id', 'packaging', 'brewery_id'
        ];

        foreach ($columns as $column){
            if (request()->has($column)){

            $products = $products->where($column, request($column));

                $queries[$column] = request($column);
         }  
        }    
        $products = $products->paginate(10)->appends($queries);
     }
}

In my blade template

<div class="col-md-2 col-centered" id="filter-bar">
     <p>Filter Products:</p>

       <a href="/products">Reset</a>

        <ul>
            <p>Types of Beer:</p>
            <li class="filter-link"><a href="/products?beertype_id=1" >IPA</a></li>
            <li class="filter-link"><a href="/products?beertype_id=2">Lager</a></li>
            <li class="filter-link"><a href="/products?beertype_id=3">Pale Ale</a></li>
            <li class="filter-link"><a href="/products?beertype_id=4">Porter</a></li>
            <li class="filter-link"><a href="/products?beertype_id=5">American Pale Ale</a></li>
            <li class="filter-link"><a href="/products?beertype_id=6">Amber Ale</a></li>
            <li class="filter-link"><a href="/products?beertype_id=7">Rye Ale</a></li>
            <li class="filter-link"><a href="/products?beertype_id=8">Hybrid</a></li>
            <li class="filter-link"><a href="/products?beertype_id=9">Red Ale</a></li>
            <li class="filter-link"><a href="/products?beertype_id=10">Saison</a></li>
            <li class="filter-link"><a href="/products?beertype_id=11">Sour Beer</a></li>
        </ul>


         <ul>
            <p>Packaging:</p>
             <li class="filter-link"><a href="/products?packaging=bottle">Bottle</a></li>
             <li class="filter-link"><a href="/products?packaging=can">Can</a></li>
             <li class="filter-link"><a href="/products?packaging=keg">Keg</a></li>
         </ul>

         <ul>
             <p>Brewery:</p>

             <li class="filter-link"><a href="/products?brewery_id=2">Kinnegar</a></li>
             <li class="filter-link"><a href="/products?brewery_id=3">White Hag</a></li>
             <li class="filter-link"><a href="/products?brewery_id=4">Quilmes</a></li>
             <li class="filter-link"><a href="/products?brewery_id=5"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=6"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=7"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=8"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=9"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=10"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=11"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=12"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=13"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=14"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=15"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=16"></a></li>
             <li class="filter-link"><a href="/products?brewery_id=17"></a></li>
         </ul>

     </div>


Would using the route() helper solve this? if so, how could i go about using it?



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

How to store user meta information for different user role in database laravel

I have different roles in my laravel application as doctor, patient, admin. Each one of different information as patient have the information about blood group, gender, infection and so on(many other fields), but doctor and admin will not have these. Doctor will have fields which patient and admin can't have. So how I can store such information in the database in better way. (I would like to retrieve the information based on these fields also).



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

Get rid of all redirects and "non-api" behaviour in laravel 5.8

I'm working with laravel for a long time now, but I'm currently facing some issues when using laravel as API-only Backend.

I want to develop the frontend seperatly and therefore treat laravle as API only. As most of things work very easily I have huge issues when writing tests.

I'm still using web middleware group (not api) and when using the auth middleware everything works when testing with postman for example, but when writing a test.

Here's a simple example:

/** @test */
public function search_competitions_unauthorized ()
{
    $response = $this->get('/competitions/ABCDEFG');

    $response->assertStatus(401);
}

Then endpoint /competitions/ABCDEFG is protected by the auth middleware.

I receive a 500 as response code because there is no route with the name login defined. This is easy to solve ofcourse (create route with name login), but I want that laravel treats every request as "api" request that does not want any redirects.

I've tried a few things in order to get rid of this behaviour:

I've defined a new class "DefaultRequest" that extends Illuminate\Http\Request

class DefaultRequest extends Request
{
  public function expectsJson()
  {
    return true;
  }

  public function wantsJson()
  {
    return true;
  }
}

And changed the index.php in the public folder to

$response = $kernel->handle(
    $request = App\Http\Requests\DefaultRequest::capture()
);

Also all the requests used in my controllers use this as their default

As I had the same issue with request validation, I've also added this method to my default request:

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(response()->json($validator->errors(), 422));
}

I have the feeling that this should be easier to resolve. It seems like in general this would only be a problem for me while testing and I could set specific headers in my tests. But I actually want to disable all these redirect behaviours as I NEVER want these for the project.



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

How to display blob from database in html tag

I am trying to display blob images from the database. When I try using HTML fragment embedding it show, but if I try using PHP it doesn't show anything.

Database:

DATABASE

I tried using the embedded strings it shows but its not coming from the database.

But when I try this code to make it display from the database it doesn't show anything.

@foreach($data as $value)

    <?php
    header("Content-Type: image/png");
    $db = mysqli_connect("127.0.0.1","root","xxxx","xxxx"); 
    $sql = "SELECT * FROM custom"; 
    $statement = $db->query($sql);
    $result = mysqli_fetch_array($statement);
    echo '<img src="data:image/png;base64,'.base64_encode($result['img_front'] ).'"/>';
    ?>

@endforeach

I want to dynamically display each blob image from the database on my web like this.

What i want to display from the database foreach blob:

what i want to display from the database foreach blob



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

How to throw exception if no data Laravel?

How to throw exception if no data Laravel when I expect some values?

$roles = Auth::user()->roles()->get();

So, is it good idea to use:

if ($roles->count() == 0) {
   throw new \Exception('No data');
}

But what if $roles are null?



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

How to get all user roles in Laravel?

I use the following article to create user roles in Laravel.

My problem is, how to get all user roles after authorization?

I tried to get roles like this:

Auth::user()->roles()

Because User model has method roles().

But it does not work.

I suppose I need to get auth user id, then to get user model:

$user = User::where('id', Auth::user()->id)->get();

And then possible I can get access to roles:

$user->roles();



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

yield not displaying content in laravel

I have moved the code of header from a template in /views/layouts/header.blade.php. When I call it using,

@yield('layouts.header')

or

@yield('header')

It doesn't display the code.



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

how to check role and permission in passport scope token in laravel and vue-cli

i have role and permission table and I want to check user role and permission in vue-cli with Auth::user()->role or Auth::user()->pemission.

Passport::tokensCan([
    'place-orders' => 'Place orders', -----> i want to check this dynamic
    'check-status' => 'Check order status', -----> i want to check this dynamic
]);
enter code here



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

samedi 30 mars 2019

Laravel, same path on a different subdomain uses wrong controller

Question

How can I set up Laravel routing so that:

  • navigating to mysite.com/login uses the LoginController
  • navigating to somecompany.mysite.com/login uses the TenantLoginController

What I'm doing

I'd have a Laravel 5.7 app that has a typical login page at say, mystite.com/login

I'd like to set up a subdomain for this app like somecompany.mysite.com that will have it's own authentication.

I'd like the somecompany users to log in at somecompany.mysite.com/login


What I've tried

The route definition for the main site login

Route::group(['namespace' => 'App\Http\Controllers\Auth', 'middleware' => ['web']], function () {
    Route::get('login',   'LoginController@showLoginForm')->name('login');
});

The rout definition for the subsomain login

Route::domain('somecompany.mysite.com')->group(function ($router) {
    $router->group(['namespace' => 'App\Http\Controllers\Tenant\Auth', 'middleware' => ['web']], function($router) {
        $router->get('login',   'TenantLoginController@showLoginForm')->name('somecompany.login');
    });
});


What Happened

I can navigate to somecompany.mysite.com/login and the URL bar says somecompany.mysite.com/login but when I do, the request is actually routed to the 'LoginController@showLoginForm' controller not the expected 'TenantLoginController@showLoginForm' and the typical login form is desplayed, not the subdomain's login form.

If I change the path to $router->get('tenant-login' and navigate to somecompany.mysite.com/tenant-login the subdomain login form is shown, and somecompany.mysite.com/login shows the main login form.



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

How create user role in JWT?

How create user role in JWT?

I need assign role when user gets token, how to do that using JWT



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

How Update Group of rows with each row data for each row

I have some artist in my db and i want to increment follower field of artist.

Now i do this work with with foreach :

   $artist_should_increment=self::whereIn('id',[1,2,3])->get();

   foreach ($artist_should_increment as $artist_increment){
             $artist_increment->update(['followers'=>$artist_increment->followers+1]);
   }

But i want to update theme with chunk method of laravel! but i don't know how to do this work beacuse i don't know how to set $artist_increment->followers+1 for each row!



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

Laravel php artisan does not wok?

When I typing this command:

php artisan cache:clear

I get this message:

In ProviderRepository.php line 208:

  Class 'Spatie\Permission\PermissionServiceProvider' not found

But how to delete this class from system, cause it was deleted from compose?



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

How return user information among JWT token?

How return user information among JWT token when user first time gets token?



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

How to make products show on homepage randomly

I was trying to make products show on homepage in a random manner.

Here's my homepage controller codes.

please help

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\Product;
use App\News;
use App\User;

class HomeController extends Controller
{
    public function Index(){
      $news = News::get();
      $products = Product::list()->paginate(20);
      $categories = Category::where("parent_id",0)->get();
      return view('index')->with([
        'news'=>$news,
        'products'=> $products,
        'categories'=>$categories,
      ]);
    }
}



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

How to guard API route using JWT laravel?

How to disable execute API requests if there is no token JWT?

No I have simple route:

Route::post('visitors/check', 'VisitorController@check');

And this code in controller VisitorController:

echo  JWTAuth::user()->id;

It fails down cause there is no token. How to handle this using JWT?



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

Laravel works on two folders in my domain

I have a Laravel project running on a shared hosting. after adding this .htaccess

RewriteEngine on
RewriteCond %{HTTP_HOST} ^site.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.site.com$
RewriteCond %{REQUEST_URI} !public/
RewriteRule (.*) /public/$1 [L]

Laravel works in site.com/ and site.com/public too.

how to let it work just in the root domain?



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

How can I loop in polymorphic relation by passing query reference?

I dont know if its called query reference. Feel free to make edits.

I have a polymorphic relation on my Article Model:

public function comments(){

        return $this->morphMany(Comment::class, 'commentable');

    }

Now I have to send a polymorphic relation data to my view.

public function show(Article $article)
    {

        return view('article.show',[
            'article' => $article,
            'comments' => $article->comments()
        ]);
    }

I'm sending it by $article->comments() because I want to use each comments eloquent relations.

On my blade:

@foreach($comments as $comment)
                 //This won't execute. What is wrong?
@endforeach

if I dd(comments) before foreach I've this: enter image description here



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

Vue: How to refresh new data?

I am using Vue Components in my blade file. Whenever I need to 'refresh' my customer object, I emit an event to the parent (shown below) and customer is refreshed and any props it passed to children will be shown with their updated values.
This is all well and good so far but I am now using some PHP values. I am passing a prop automatic-payments-enabled and it's using a php value. How can I have that value refresh after making an API call that changes it?

Blade file

<div id="app">

   <Account 
     :customer="customer"
     :automatic-payments-enabled={!! json_encode($customer->automaticPaymentsEnabled()) !!}
   >
</div>

app.js

Vue.component('Account', 
    require('./components/Account.vue').default);

new Vue({
    el: "#app",
    data() {
        return {
            customer: null
                       }
                }
        mounted() {
            this.getCustomer();
        }
        methods: {
            getCustomer: function() {
                 //api call to server
                 this.customer = response.data
            } 
        }
}



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

Call to undefined method App\User::gravatar() While the method exist

Please I'm new to Laravel. I kept on having issue each time I try to define a use an if statement or declare variable in the view.

Actually Im trying to display a gravatar in my Admin Dashboad. All I get is: Call to undefined method App\User::gravatar() (View: C:\wamp64\www\blog\resources\views\layouts\backend\navbar.blade.php)

<ul class="nav navbar-nav">
              <li class="dropdown user user-menu">

                <?php $currentUser = Auth::user()  ?>

                <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              <img src="  " class="user-image" alt=" ">
                  <span class="hidden-xs"></span>
                </a>
                <ul class="dropdown-menu">
                  <!-- User image -->
                  <li class="user-header">
                    <img src="
                    " class="img-circle" alt="User Image">

                    <p>
                       - Web Developer
                      <small>Member since Nov. 2012</small>
                    </p>
                  </li>
                  <!-- Menu Footer-->
                  <li class="user-footer">
                    <div class="pull-left">
                      <a href="#" class="btn btn-default btn-flat">Profile</a>
                    </div>
                    <div class="pull-right">
                            <a class="btn btn-default btn-flat"
                            href=""
                            onclick="event.preventDefault();
                            document.getElementById('logout-form').submit();">Logout
                            </a>

                            <form id="logout-form" action="" method="POST" style="display: none;">
                              
                            </form>
                    </div>
                  </li>
                </ul>
              </li>
            </ul>




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

Unable to group the two Middlewares

I am trying to implement 3 user types in to my application, I am using the default Auth of Laravel.

I created 2 extra middlewares to acheive the to extra user(admin & Districtlogin) conditions along with user approval middleware, and using the default for laravel user

Admin middleware

class Admin
{
   tion handle($request, Closure $next)
    {
        if( Auth::check() && Auth::user()->isAdmin == 1)
        {
            return $next($request);
        }
            Auth::logout();
            return redirect('login')->with('error','You have not admin access');
        }
}

Districtlogin Middleware

class Districtlogin
{
    public function handle($request, Closure $next)
    {
        if (Auth::check() && Auth::user()->isAdmin == 2) {
            return $next($request);
        }
        Auth::logout();
        return redirect('login')->with('error', 'You have not admin access');
    }
}

One additional middleware to check if the user is approved

class ApproveUser
{

    public function handle($request, Closure $next)
    {

        if( Auth::check() && Auth::user()->row_status == 1)
    {
        return $next($request);

    }
            return redirect('/userapprove');

    }

I am able to redirect them based on the login

Auth/LoginController

 public function redirectPath()
    {
        if (Auth::user()->isAdmin == 1 && Auth::user()->row_status == 1) {
            return '/adminindex';
        } elseif (Auth::user()->row_status == 0) {
            return '/userapprove';
        } elseif (Auth::user()->isAdmin == 2 && Auth::user()->row_status == 1) {
            return '/districtindex';
        }
        return '/engineerdashboard';
    }

Here is my

kernel.php

entry

'admin' => \App\Http\Middleware\Admin::class,
'districtlogin' => \App\Http\Middleware\Districtlogin::class,
'userapprove' => \App\Http\Middleware\ApproveUser::class,

I would like to group the admin and Districtlogin middleware.

I am using CRUD, I would like Districtlogin to have access to few controllers - index,store,update

When I try to group the middleware, I am redirected back to the login screen. Neither of the middleware works

Here's what I tried,

1)

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

    //Admin Dashboard
    Route::resource('adminindex', 'AdminindexController')->middleware('districtlogin');
    Route::get('adminindex/new', 'AdminindexController@admindashboard');
});

2)

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

    //Admin Dashboard
    Route::resource('adminindex', 'AdminindexController');
    Route::get('adminindex/new', 'AdminindexController@admindashboard');

});

3)

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

        //Admin Dashboard
        Route::resource('adminindex', 'AdminindexController');
        Route::get('adminindex/new', 'AdminindexController@admindashboard');

        Route::middleware(['districtlogin'])->group(function () {
        Route::resource('adminindex', 'AdminindexController');

           });

    });

But when I use the 'OR' condition, I am able to access the pages

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

    //Admin Dashboard
    Route::resource('adminindex', 'AdminindexController');
    Route::get('adminindex/new', 'AdminindexController@admindashboard');
});

The controllers are accessible by both the middlewares. But how do I limit the Crud functions based on the middleware.

I am completely clueless on how to achieve it.



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

How to auto list (auto complete) the methods of parent classes and used traits in Sublime for Laravel

Sublime ctrl+space and ctrl+r shortcuts dropdown some methods, but I think I need more. In an example:

Illuminate\Foundation\Auth\User.php

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
}

Laravel's default User model extends above like that:

app/User.php

<?php

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

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

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

Now in the controller I can use User model. And what I want is that when I type User:: and ctrl+"some super shortcut" I expect to see parent-parent class's (e.g. Model) methods like getKeyName() and the methods of Authenticatable, Authorizable, CanResetPassword traits. But typing ctrl+space results in swarms of methods I don't know, and I can't find the desired methods. Should I open parent class files every time?



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

Searching for arabic words

i have an issue in searching in laravel with arabic words if i have two words like [عماره,عمارة] the difference between them is last letter ه and ة in the normal method for search by using " LIKE " and i wrote عماره it come with the same word not the two words how to handle it and get the two words ?



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

How to pass URI to controller with Laravel and not get 404 error?

I have a fresh installation of Laravel 5.8. I want to pass the URL of the application as a parameter to my controller. I am getting error 404 every time I try to enter something different from https://webapp.dev/

How can I avoid this 404 and send the URL to a controller like a parameter?

If I do this https://webapp.dev/url-one I want to get in my controller the url-one and not get a 404 error.



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

Duplicate entry even on blank DB

I'm trying to implement JWT for my users. When I attempt to register I keep getting an error saying a user with the same email already exists. Even when I run off a blank users table.

The user is created once, so I don't know what the issue is. I'm attempting this in Postman.

Any ideas here

public function getToken($email, $password)
{
    $token = null;
    //$credentials = $request->only('email', 'password');
    try {
        if (!$token = JWTAuth::attempt( ['email'=>$email, 'password'=>$password])) {
            return response()->json([
                'response' => 'error',
                'message' => 'Password or email is invalid',
                'token'=>$token
            ]);
        }
    } catch (JWTAuthException $e) {
        return response()->json([
            'response' => 'error',
            'message' => 'Token creation failed',
        ]);
    }
    return $token;
}

public function register(Request $request)
{ 
    $payload = [
        'password'=>\Hash::make($request->password),
        'email'=>$request->email,
        'username'=>$request->username,
        'auth_token'=> ''
    ];

    $user = new \App\User($payload);
    if ($user->save())
    {

        $token = self::getToken($request->email, $request->password); // generate user token

        if (!is_string($token))  return response()->json(['success'=>false,'data'=>'Token generation failed'], 201);

        $user = \App\User::where('email', $request->email)->get()->first();

        $user->auth_token = $token; // update user token

        $user->save();

        $response = ['success'=>true, 'data'=>['name'=>$user->name,'id'=>$user->id,'email'=>$request->email,'auth_token'=>$token]];        
    }
    else
        $response = ['success'=>false, 'data'=>'Couldnt register user'];


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



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

test laravel database with existsing real data

I have a huge database and using laravel for my web application. and migrate old data to the new data

I want to write unit test for my application I need to test the real database with real data and factory make some fake data and insert theme to the real database and I need to remove them. I use DatabaseTransactions trait but this is not working

I need after test remove all the fake data that inserted in the database



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

How can I create a polymophic relation factory so that I can use it on my phpunit tests?

I have articles table and comments table. comments table includes commentable_id commentable_type and body. I tried the code below on my testcase which doesn't seem right. With this one I cannot create multiple comments.

/** @test */
    public function an_authenticated_user_can_comment_a_post(){

        $user = $this->signIn();

        $article = factory('App\Article')->create();

        $this->post("article/{$article->slug}/comment", [
            'comment' => $this->faker->sentence,
        ]);

        $this->assertCount(1, $article->comments);

    }



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

Submit button not working when there are multiple fields present

When there is multiple address generated, the Submit button does not work.

I've tried to solve it with JavaScript.

                   @foreach ($userDetails as $addr)
                       <div class="order_container">
                           <input type="hidden" name = "userName" value="" >
                           <input type="hidden" name = "userMobile" value="" >
                           <input type="hidden" name = "userSelectAddress" value="" >
                           <input type="checkbox" name="userSelectAddressId" value="" id="id1"/>


                            <br>
                            <br>
                            <br>
                           <br>
                       </div>
                   @endforeach

JS

function validate_radio(){
            /*alert("fail");
            return false;*/
           // let inpObj = document.getElementById("id1").value.checked;
            if(document.getElementById('id1').checked){
                alert("pass");
            }
            else {
                alert("else");
                return false;
            }
        }

I expect the submit button to work no matter how many address i have selected.

Thank you in advance.



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

How to upload multiple files in laravel and angular 7?

I am using angular 7 with laravel for backend.I am having one form where i have one dropdown with list of companies. User will select particular company onchange company i am displaying one html table with list of employees of particular company.

Code of html table :

<table *ngIf="allemp" >
<tr>
    <th>ID</th>
    <th>Name of Employee</th>
    <th>Attached Payslip</th>
</tr>
<tr *ngFor="let data1 of allemp">
    <td></td>
    <td></td>
    <td><input type="file" (change)="onFileChangeInfo($event)" multiple></td>
</tr>
</table>

As you can see in last td i am having input type file from where i want to add each employees of different salary slips into database.

My function in ts file to get multiple files:

  onFileChangeInfo(event) {
    console.log(event);
      const reader = new FileReader();
        if(event.target.files && event.target.files.length > 0) {
          const [file] = event.target.files;
          reader.readAsDataURL(file);
            console.log(file);
          reader.onload = () => {
            this.myForm1.patchValue({
              'inv_blob': reader.result,
              'inv_pdf':file.name,
          });
            this.cd.markForCheck();
          };
      }
  }

On console.log(file) i am able to get each files. but in backend api only goes last file.

I am not able to get all files that i am getting into console.log(file) in my backend.

$blob_payslip = $request->inv_blob;
                $filename_contract =$request->inv_pdf;
                $paySlipUpload = CapsMaster::UploadFile1($blob_payslip,$this->payslipfolder,'abc',$filename_contract);
                $payslip_data->inv_pdf='payslips/'.$billing_com.'/'.$paySlipUpload;

I tried with foreach loop but its not working for me.I want to store different rows for each selected file into database. please help me with the same.send me some links if possible for same. because i google for this issue but not getting proper answers.



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

vendredi 29 mars 2019

Removing redirect for specific route groups

I'm looking to create a route group that enables particular users to view information on my site without being authenticated.

At the moment, i've created a route service provider called 'public' as follows:

Route::get('customer/application', function () {
    return view('customerview.customer-application');
});

When I write 'php artisan route:list' the following comes up for the route:

Method: GET | HEAD URL: customer/application Middleware: ''

I have removed all middleware in an attempt to bypass auth, but with no luck.

The area which is redirecting me to the login page is here in App\Exceptions\Handler.php:

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }
    return redirect()->guest('login');
}

I also tried assigning the route to 'guest' group but no help. How can I bypass the return redirect()->guest('login'); for different groups?



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

"Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: users" on using SQLite :memory: for phpunit testing in Laravel 5

I'm using SQLite :memory: for only phpunit testing in Laravel whereas all my actual database data (all tables) are in MySQL which I use for development and are working fine when I manually test it. I'm not familiar with how SQLite :memory: works and if I have to separately create database and tables for it when I'm using it to write tests? or does :memory: does that itself?

I expect my phpunit tests to pass but I get

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: users

Here is my phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
    </php>
</phpunit>

Here is the test I'm running:


   /** @test */
   public function user_can_view_questions()
   {
       $question = factory('App\Question')->create();
       // not writing the rest of code as this returns as an error

   }

and here is the factory if it is needed:

<?php

use App\User;
use Illuminate\Support\Str;
use Faker\Generator as Faker;
use App\Question;
use App\Answer;


$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

$factory->define(Question::class, function (Faker $faker) {
    return [
        'user_id' => function(){
            return factory('App\User')->create()->id;
        },
        'subject_id' => $faker->randomDigit,
        'class_id' => $faker->randomDigit,
        'chapter_id' => $faker->randomDigit,
        'topic_id' => $faker->randomDigit,
        'qnop' => $faker->sentence,
        'qtitle' => $faker->sentence,
        'qdetails' => $faker->sentence
     ];
});

$factory->define(Answer::class, function (Faker $faker) {
    return [
        'user_id' => function(){
            return factory('App\User')->create()->id;
        },
        'question_id' => function(){
            return factory('App\Question')->create()->id;
        },
        'rating' => $faker->numberBetween($min = 0, $max = 5),
        'ans' => $faker->sentence
     ];
});




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

How to apply the CRUD generator for Laravel module architecture?

I have been created a module in Laravel 5.8 by using the following command.

php artisan module:make leave

A leave module structure is created. But how can I create a CRUD operation in this module by using the infyom (or another) CRUD generator?



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

Laravel DB::raw bind parameters

I have problem when trying to bind the data in to query. I'm use php framework Laravel 5.7 version.

Trying to bind data this way:

DB::raw("(
        select 10 * FLOOR(SUM(TIME_TO_SEC(TIMEDIFF(end_time, start_time)) - 3600 )  * (drivers.salary_per_hour / 3600) / 10)
        from assignments
        where assignments.driver_id = drivers.id 
        and assignments.driving_day between STR_TO_DATE('?', '%Y-%m-%d') and STR_TO_DATE('?', '%Y-%m-%d') ) as salary",[
            $dates['from'],
            $dates['to']
        ])

and receive null as result.

$dates array values:

['from' => '2019-03-01', 'to' => '2019-03-31']

But if I'm doing it this way it work fine, but there is SQL injection, and I'm think it will be better if I'm bind the data.

$drivers = Driver::select([
        'id', 'name', 'surname', 'phone', 'driver_status','driver_status', 'updated_at', 'updated_at', 'photo',
        'salary_per_hour',
        DB::raw("(
            select 10 * FLOOR(SUM(TIME_TO_SEC(TIMEDIFF(end_time, start_time)) - 3600 )  * (drivers.salary_per_hour / 3600) / 10)
            from assignments
            where assignments.driver_id = drivers.id 
            and assignments.driving_day between STR_TO_DATE('".$dates['from']."', '%Y-%m-%d') and STR_TO_DATE('".$dates['to']."', '%Y-%m-%d') ) as salary"),
        DB::raw("(
            select SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(end_time, start_time)) - 3600 ))
            from assignments
            where assignments.driver_id = drivers.id 
            and assignments.driving_day between STR_TO_DATE('".$dates['from']."', '%Y-%m-%d') and STR_TO_DATE('".$dates['to']."', '%Y-%m-%d') ) as worked_hours"),
    ])->whereHas('assigments', function ($query) use ($dates) {
        $query->whereBetween('driving_day', [$dates['from'], $dates['to']]);
    });

    $table = $drivers->paginate(15);

What's wrong in my data binding?



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

hasManyThrough relationship in Laravel 5.8

I have the following struct:

Order
 id

Order_Products
 id
 order_id
 product_id

Products
 id

Im trying to use hasManyTrough (https://laravel.com/docs/5.8/eloquent-relationships#has-many-through).

I have something like

class Order extends Model{
...
public function products()
{
    return $this->hasManyThrough('App\Product', 'App\OrderProduct', 'product_id', 'id', 'order_id', 'id');
}
...
}

I can not make it work. I'm confused, can someone help me.



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

How to create roles in Laravel Passport?

I want to assign specific role for registered user to distinct access in application. As instance I need roles: admin, operator.

Is it possible to do with Laravel Passport?

Whats difference between grand and role?



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

CORS Laravel 5.7 does not work correct, is itcore bug?

I use Laravel 5.7 and middleware is:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

      header('Access-Control-Allow-Origin: *');


        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            return Response::make('OK', 200, $headers);
        }


        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;

    }
}

I have registered this in Kernel.php:

protected $routeMiddleware = [
    'cors' => \App\Http\Middleware\Cors::class
];

So, when browser sends OPTION request server returns the following instead CORS settings:

enter image description here

Route is:

Route::group(['middleware' => ['cors']], function () {
});

It means cors middleware does not work correct.

I tried simple test:

public function handle($request, Closure $next)
{

   echo 'test';

}

Server does not return me echo 'test'; when request is sending



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

Convert int column with timestamp value into date format (Y-m-d)

I have sql-server column called (date) with int type and the value for this column is timestamp like (1538254800) i need to select this column from my laravel sql query and appear it as date format (Y-m-d H:m:i pm) like (2018-09-29 09:00:00 pm)



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

Php random username and password generate for login

i have been trying to build a login system in which persons just input normal information in the signup form in submitting the system generates a user name and password and sends it to the person to login with



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

Laravel mysql access denied while package:discover command

I have cloned a new project. and just ran the composer install command. All packages are installed perfectly But I got an error while "post-autoload-dump". The error says

    In Database.php line 154:

  Database error: SQLSTATE[HY000] [1045] Access denied for user ''@'localhost  
  ' (using password: NO) 

I changed credentials for the database in .env file and ran the composer install again. But got the same error again. When I tried to run php artisan config:clear It also returned the above error.



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

How to add Edit and Delete function in my FullCalendar laravel ph?

I'm doing a project in laravel, where I can show my list of events using fullcalendar. I already created/have a fullcalendar view with events and adding event, but I want to be able to click the date and edit it or delete it.

Sample event fullcalendar

I already search some solutions or guides for this, but I can't work it properly. I tried creating another one from scratch but it doesn't work.

Here are the links that I searched and doing it as my guide.

FullCalendar Events and Scheduling

github driftingruby/042-fullcalendar

This is my codes in my create.blade.php

<div class="container">

    <div class="panel panel-primary">

        <div class="panel-heading">Event Calendar</div>

            <div class="panel-body">
                {!! Form::open(array('route' => 'admin/events.create','method'=>'POST','files'=>'true')) !!}
                    <div class="row">
                        <div class="col-xs-12 col-sm-12 col-md-12">
                            @if (Session::has('success'))
                                <div class="alert alert-success"></div>
                            @elseif (Session::has('warning'))
                                <div class="alert alert-danger"></div>
                            @endif
                        </div>

                <div class="col-xs-4 col-sm-4 col-md-4">
                    <div class="form-group">
                        {!! Form::label('event_name','Event Name:') !!}
                        <div class="">
                        {!! Form::text('event_name', null, ['class' => 'form-control']) !!}
                        <!-- {!! $errors->first('event_name', '<p class="alert alert-danger">:message</p>') !!} -->
                        </div>
                    </div>
                </div>

                <div class="col-xs-3 col-sm-3 col-md-3">
                    <div class="form-group">
                        {!! Form::label('start_date','Start Date:') !!}
                        <div class="">
                        {!! Form::date('start_date', null, ['class' => 'form-control']) !!}
                        <!-- {!! $errors->first('start_date', '<p class="alert alert-danger">:message</p>') !!} -->
                        </div>
                    </div>
                </div>

                <div class="col-xs-3 col-sm-3 col-md-3">
                    <div class="form-group">
                        {!! Form::label('end_date','End Date:') !!}
                        <div class="">
                        {!! Form::date('end_date', null, ['class' => 'form-control']) !!}
                        <!-- {!! $errors->first('end_date', '<p class="alert alert-danger">:message</p>') !!} -->
                        </div>
                    </div>
                </div>

                <div class="col-xs-1 col-sm-1 col-md-1 text-center"> &nbsp;<br/>
                {!! Form::submit('Add Event',['class'=>'btn btn-primary']) !!}
                </div>
            </div>
            {!! Form::close() !!}

        </div>
    </div>

    <div class="panel panel-primary">
        <div class="panel-heading">Event Details</div>
            <div class="panel-body">
                {!! $calendar_details->calendar() !!}
            </div>
        </div>  
    </div>

    <link rel="stylesheet" href="https://cdjns.cloudfare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css"/>

<!-- Scripts -->
<script src="http://code.jquery.com/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.js"></script>

{!! $calendar_details->script() !!}

And this is my code for my AdminEventsController

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events;
use App\Barangay;
use Illuminate\Support\Facades\Auth;
use Session;
use Calendar;


class AdminEventsController extends Controller
{
     public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

     public function index() {
        $events = Events::get();
        $event_list = [];
        foreach ($events as $key => $event) {
            $event_list[] = Calendar::event(
                $event->event_name,
                true,
                new \DateTime($event->start_date),
                new \DateTime($event->end_date.' +1 day')
            );
        }

        $calendar_details = Calendar::addEvents($event_list);

        return view('admin.events.create', compact('calendar_details') );
    }

    public function addEvent(Request $request)
    {
        $mybrgyid = Auth::user()->brgyid;
        $mybarangay = Barangay::select('brgyname')->where('id', $mybrgyid)->get();
        session(['mybarangay' => $mybarangay]);

        $this->validate($request,[
            'event_name' => 'required',
            'start_date' => 'required',
            'end_date' => 'required'
        ]);

        //$validator = validator::make($request->all(), [
            //'event_name' => 'required',
            //'start_date' => 'required',
            //'end_date' => 'required'
        //]);

        //if ($validator->fails()) {
        //  \session::flash('warning', 'Please enter the valid details');
        //  return Redirect::to('/admin/events')->withErrors($validator);
        //}

        $event = new Events;
        $event->brgyid = Auth::user()->id;
        $event->event_name = $request['event_name'];
        $event->start_date = $request['start_date'];
        $event->end_date = $request['end_date'];
        $event->save();

         return redirect('/admin/events')->with('success', 'Event Created');
    }
}

Somehow I'm being confuse as to where I would create a modal for editing and deleting an event in my fullcalendar.

Your help is much appreciated.



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

Laravel - Route can't be found when I added in a request validator

I have a function to handle payments on my site. When I change Request $request to PropertyPaymentRequest $request

Is there any reason why?

public function ProcessAdvertPayment(Property $property, PropertyPaymentRequest $request)
    {

        $payload = $request->input('payload', false);
        $nonce = $payload['nonce'];

        $payment = Braintree_Transaction::sale([
            'amount' => 1,
            'paymentMethodNonce' => $nonce,
            'creditCard' => ['number' => request('cardnumber'), 'expirationDate' => request('month') . '/' . request('year'), "cvv" => request('cvv')],
        ]);

        if($payment->success)
        {
            $property->payment()->create($request);
        }

        return response()->json($payment);
    }

Thanks



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

How do i fix this Jquery error 405 (Method Not Allowed)

When i try to debug, i get this error:

jquery.js:6 POST http://localhost/public/product/check-pincode 405 (Method Not Allowed)

I change the jquery version thinking that is the problem, but am still getting localhost error.

jquery

function checkPincode(){

var pincode = $("#chkPincode").val();
if(pincode==""){
    alert("Please enter your Pincode"); return false;
}
$.ajax({
     type:'POST',
     data:{pincode:pincode},
     url:'/check-pincode',
     success:function(resp){
         alert(resp);
     },error:function(){
         alert("Error");
     }
});

HTML

   <P><input type="text" name="pincode" id="chkPincode" placeholder="Check Pincode"><button type="button" onclick="return checkPincode();">Go</button></p>

CONTROLLER

public function checkPincode(Request $request){
     if ($request->isMethod('post')){
         $data = $request->all();
         echo "<pre>"; print_r($data); die;
     }

}

ROUTE

// Check Pincode

Route::post('/check-pincode','ProductsController@checkPincode');



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

How setting laravel-websockets url under /admin to protect it?

Using beyondcode/laravel-websockets packege I can modify config option

'path' => ‘admin/laravel-websockets’ 

to run it under admin, but how to protected access to it to logged user with admin rights, as in my routes/web.php I have group :

Route::group(['middleware' => ['auth', 'isVerified', 'CheckUserStatus'], 'prefix' => 'admin', 'as' => 'admin.'], function () {

Thanks!



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

Laravel nova multiselect edit not working

I'm using laravel nova for creating an admin panel. This is my code.

Laravel nova resource,

use Nova\Multiselect\Multiselect;

public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),            
            Multiselect::make(__('Day'),'day')
                ->options($this->getweedkDay()),
        ];
    }

private function getweedkDay(){
        $weekDay = [];

        $weekDay[1] = __('Sunday');
        $weekDay[2] = __('Monday');
        $weekDay[3] = __('Tuesday');
        $weekDay[4] = __('Wednesday');
        $weekDay[5] = __('Thursday');
        $weekDay[6] = __('Friday');
        $weekDay[7] = __('Saturday');


        return $weekDay;
    }

I'm using this plugin for multi select and date field is a varchar field in database. The issue is even I can select items and save them in db they will not be able to see in edit view or index view for nova resource. it would be great if someone can help



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

Valid syntax for excludeTables using laravel-backup

Using laravel-backup("^6.1") for laravel 5.8

I failed to set excludeTables property in config file. I did it as :

'source' => [
...
    'databases' => [
        'mysql',
    ],


     'mysql' => [
         'dump' => [
             'excludeTables' => [
                 'activity_log', //Without prefix  vt2_activity_log
                 'migrations'
             ]
         ]
     ],

But I see that all tables including vt2_activity_log and vt2_migrations are in resulting file?

vt2_ that is an prefix defined in config/database.php :

'mysql' => [
    'driver' => 'mysql',
    'prefix' => 'vt2_',
    ...

I suppose that I do not have to set prefix in excludeTables array ? I tried both, but failed. Was it correct place/synatx for excludeTables?

Thanks!



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

How to host laravel 5.7 on a shared server

I am failing to make laravel 5.7 work on shared hosting.

I tried to use the following tutorials: - https://medium.com/laravel-power-devs/deploy-laravel-projects-on-shared-hosting-2008be6f6f03 - and this one too https://medium.com/laravel-news/the-simple-guide-to-deploy-laravel-5-application-on-shared-hosting-1a8d0aee923e.

but non of them solved my problem, even all the stackoverflow questions about this same topic didn't help me. Please help., i spent more than 1:30 minutes hours on this till now i havent got any solution.



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

How to handle this migration error in laravel?

I am working in a restaurant system and I am adding a table to the database and have a problem with create_menus_table I think the problem is in the relations between tables but I can't find it.

I tried to delete all of them and made models again and checked whether the error in the tables or not and delete the database and delete all modules

the error in cmd

**Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1 (SQL: alter table menus add constraint menus_user_id_foreign foreign key (user_id) references users ()) at C:\xampp\htdocs\laravelrestaurantapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664 660| // If an exception occurs when attempting to run a query, we'll format the error 661| // message to include the bindings with SQL, which will make this exception a 662| // lot more helpful to the developer instead of just the database's errors. 663| catch (Exception $e) {

664| throw new QueryException( 665| $query, $this->prepareBindings($bindings), $e 666| ); 667| } 668| Exception trace: 1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1") C:\xampp\htdocs\laravelrestaurantapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452 2 PDO::prepare("alter table menus add constraint menus_user_id_foreign foreign key (user_id) references users ()") C:\xampp\htdocs\laravelrestaurantapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452 Please use the argument -v to see more details.**

the menus table

    <?php

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

class CreateMenusTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('menus', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->string('type');
            $table->text('description');
            $table->boolean('status');
            $table->string('image');
        // to make relation with the users table as the menu has several users
        // as one to many relationship
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->reference('id')->on('users');

        $table->timestamps();
    });
}

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

}



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