Friday, March 31, 2017

File::copyDirectory return nothing

I'm able to copy files using Storage::copy but when i tried to copy folder with File::copyDirectory, it doesn't change anything. Why is that?

My Code:

 public function pasteDocument(Request $request)
    {      
      if(Session::get('clipboard') == "copy"){
      // copy to disk
          File::copyDirectory('public\img', 'public\js', true);
         }
      return redirect()->back();
    }



via Dikna R Yahdi

PHP-MYSQL user clicks current time entered, next page locked until 24 hours passed

Through php mysql how to achieve when a user clicks time is logged in mysql with his id in mysql . when he clicks the next page timer shows the remaining time of 24 hours . after the remaining time ends page is unlocked for the user.

Detail script needed.. Thankyou for help.



via Jenny

elastic searcl with laravel 5.4

I'm a newbie to elasticsearch and wanted to implement it in my project everytime I input something it give an error- NoNodesAvailableException in StaticNoPingConnectionPool.php line 51: No alive nodes found in your cluster



via abhishek

Descending order in yajra not working properly for second page onwards

For ascending sort , yajra is working properly(means response has properly sorted data). I have an array like this:

suppose i have :

$order = $order_data [0]['dir']
$column = $order_data[0]['column']
$length = 6;
$start = 6;

My Table datatable with id as ascending goes like this :

[
0=>["Id"=>"111", "name"=>"jack", "age"=>"23"]
1=>["Id"=>"112", "name"=>"harry", "age"=>"12"]
2=>["Id"=>"113", "name"=>"babu", "age"=>"23"]
3=>["Id"=>"114", "name"=>"ravi", "age"=>"43"]
4=>["Id"=>"115", "name"=>"suman", "age"=>"45"]
5=>["Id"=>"116", "name"=>"david", "age"=>"54"]
6=>["Id"=>"117", "name"=>"kiran", "age"=>"53"]
7=>["Id"=>"118", "name"=>"arjay", "age"=>"78"]
8=>["Id"=>"119", "name"=>"alien", "age"=>"23"]
9=>["Id"=>"120", "name"=>"steve", "age"=>"34"]
10=>["Id"=>"121", "name"=>"elon", "age"=>"34"]
]

My back end implementation is this:

//$results contains the results after sorting
$results = $model->getPeopleSortedById($start, $length, $order);

$dataForDT = new Collection();
foreach ($results as $ds) {
            $dataForDT->push($ds);
        }

return Datatables::of($dataForDT)
->with(['recordsTotal' => (int)$totalRecords, 'recordsFiltered' => 
(int)$totalRecords])
->make('true');

I am getting response for test cases :

Test case : 2

Response: data:[]

order[0][column]:0
order[0][dir]:asc
start:10
length:10

Test case : 2

Response : data:[]

    order[0][column]:0
    order[0][dir]:desc
    start:10
    length:10

For temporary solution I am doing this :

//$results contains the results after sorting
$results = $model->getPeopleSortedById($start, $length, $order);

$dataForDT = new Collection();
$mDataSupport = 'true';
$orderFirst = 'false';

if ($order == "desc") {
        $orderFirst = 'false';
    }

if($order=="asc"){
       $temp =["Id"=>"", "name"=>"", "age"=>""];
} else {
       $temp =["Id"=>"999999999", "name"=>"zzzzzzzzzzz", "age"=>"99999999"];
}

$results = array_pad($results , (-((int)$start + count($results))), $temp);

foreach ($results as $ds) {
            $dataForDT->push($ds);
        }

return Datatables::of($dataForDT)
->with(['recordsTotal' => (int)$totalRecords, 'recordsFiltered' => 
(int)$totalRecords])
->make('true');

Now data is coming properly. Is it a bug of Yajra or what ?



via subhajit

Laravel Auto-Link library

I'm looking for a travel auto-link detection.

I'm trying to make a social media website and when my users post URLs I need it so like shows instead of just normal text.



via Jack Douglas

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

I have uploaded my project on my hosting ..But when i tried to access form url I got the following Error

QueryException in Connection.php line 647:
SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

I have changed the following credentials of .env

DB_DATABASE=cpanel_database
DB_USERNAME=cpanel_db_name
DB_PASSWORD=cpanel_db_password

What could be the error for getting the Above Error?



via User57

showing each single image of products in laravel

I have double tables one for products and one for files, files table have multi images related to the one product.

I want to show only one image for each product not all of them.

I make this code but it's back with the for example 3 times with the first image!

@foreach($lastProducts as $key => $lastProduct)
@if($key == 1)
<div class="bl-thumb">
<img src="">
</div>
@endif
@endforeach

I need to show the first image at my page and other pages show the second and third image for the product.

And here's my view which want to show all images on it :

<div class="slim-scroll">
    <div class="item active">
        <a href="" title="" data-lg-img="/website/images/" class="pic"><img src="/website/images/" alt="" class="img-responsive" /></a>
    </div>
    <div class="item">
        <a href="javascript:void(0)" title="" data-lg-img="/website/images/" class="pic"><img src="/website/images/" alt="" class="img-responsive" /></a>
    </div>
    <div class="item">
        <a href="javascript:void(0)" title="" data-lg-img="/website/images/" class="pic"><img src="/website/images/" alt="" class="img-responsive" /></a>
    </div>
    <div class="item">
        <a href="javascript:void(0)" title="" data-lg-img="/website/images/" class="pic"><img src="/website/images/" alt="" class="img-responsive" /></a>
    </div>
</div>

It's showing me something like that without the foreach

enter image description here enter image description here



via Dina Shaldoum

laravel5.2 errors not show up in blade

I am trying solve this wired problem for hours,but still the errors message won't show up in template. I have make sure the web middleware (which contains StartSession and ShareErrorsFromSession) is wrapped all my route.

all routes inside the web middleware

validation goes like :

validation code

[blade code][3]

please help!

the validation is worked, but the errors vanished



via Xin

Laravel: QueryException in Connection.php line 647

I want to create an admin page for deleting images.

In admin.blade.php:

@if (Auth::check())
@foreach ($images as $image)
<img height='100px' width='100px' src="storage/images/" alt="Image "></p>
<form action="image//delete" method="post">
<button type="submit">Delete image</button> 
<br>
@endforeach
@else
<p>Login first</p>
@endif

In routes/web.php:

//deleting images
Route::post('image/{id}/delete', 'ImageController@destroy');

In App/Http/Controllers/ImageController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;
class ImageController extends Controller
{
    public function destroy($id)
    {
        $image = Image::findOrFail($id);
        $image->delete();

        return redirect('admin');
    }
}

Upon clicking the Delete image-button, I get this lengthy error message:

QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`retellgram`.`captions`, CONSTRAINT `captions_image_id_foreign` FOREIGN KEY (`image_id`) REFERENCES `images` (`id`)) (SQL: delete from `images` where `id` = 1)

Why does this happen?

EDIT: Migrations for Images and Captions, as requested in the comments.

From 2017_03_10_080608_Create_Image_Table.php:

<?php

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

class CreateImageTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('file_path');
            $table->string('md5')->index();
            $table->integer('likes')->default(0);
            $table->timestamps();
        });
    }

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

From 2017_03_20_1104_35_create_caption_table.php:

<?php

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

class CreateCaptionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('captions', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('image_id')->unsigned();
            $table->foreign('image_id')->references('id')->on('images');

            $table->string('content');
            $table->integer('likes')->default(0);
            $table->boolean('approved')->default(false);

            $table->integer('character_id')->unsigned();
            $table->foreign('character_id')->references('id')->on('characters');

            $table->timestamps();

        });

        Schema::create('caption_hashtag', function (Blueprint $table) {
            $table->integer('caption_id')->unsigned()->index();
            $table->foreign('caption_id')->references('id')->on('captions')->onDelete('cascade');

            $table->integer('hashtag_id')->unsigned()->index();
            $table->foreign('hashtag_id')->references('id')->on('hashtags')->onDelete('cascade');

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

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



via Sandi

How to host laravel project on subfolder

I have put my laravel project on a public_html And i put my public folder inside a of subfolder and i have changed following two lines inside of my index.php file.

to this:

require __DIR__.'/../admin/bootstrap/autoload.php';
$app = require_once __DIR__.'/../admin/bootstrap/app.php'; 

This is my folder structure inside of my public_html:

Admin (My Laravel Project without public folder) Cart (I put all contents of my public folder here)

As i wanted to run my project with a static website..i follow that structure.. like .. www.mywebsite.com/cart it should load my admin application

I got http error 500 when i tried to access www.mywebsite.com/cart

Thank in advance if you could help me to find it out.



via User57

Check Joomla Version from custom app

I am Creating a custom App in Laravel 5.4 which allows me to check Joomla versions of all my installations.

This will allow me to check everything in one place. Can someone tell me how do i accomplish this?

Ashish



via ashish

Composer require laravel/installer fail

i tried to install laravel 5.4 using composer 1.4 on windows 8 composer global require "laravel/installer". but it took a long time and always fail. the error message is

[composer\Downloader\TransportException] Content-Length mismatch

i tried to install passport laravel composer require laravel/passport but it gives me the same content-length mismatch result.

what happend with my composer?



via Wildan Ainurrahman

WordPress + Facebook login to sign up subscribers: Is this a good idea?

I have a website that users could register to save some preferences and I'm planning to use Facebook login to make the sign up / sign in easier.

Problem is: It does not seem to be an easy task to manage users that came from Facebook by hand. Mainly because I want the default WordPress admin area decoupled from the "common" users and I would like to store some information about the user into database which I don't know if fits WordPress patterns.

Is there some plugin or methodology that helps with this management? Is this even a good idea?

I'm experienced doing this really easely with Laravel, but WordPress admin interface and post structure would help a lot to manage the site's content.



via juniorgarcia

Webpack: There's some JavaScript code in the compiled file even when the source file is empty

I'm using Laravel and Laravel Mix. Out of the box, the included app.js file bootstraps quite a few dependencies like jQuery, Bootstrap-sass etc.

When I delete everything in the app.js file, why is there still some code in the compiled js file? Is it a Webpack thing? Even after running npm run production it stays there and I haven't been able to figure out what it does or what it means and not knowing makes me really uncomfortable.

Here's the code that gets left behind:

! function(n) {
function t(e) {
    if (r[e]) return r[e].exports;
    var o = r[e] = {
        i: e,
        l: !1,
        exports: {}
    };
    return n[e].call(o.exports, o, o.exports, t), o.l = !0, o.exports
}
var r = {};
t.m = n, t.c = r, t.i = function(n) {
    return n
}, t.d = function(n, r, e) {
    t.o(n, r) || Object.defineProperty(n, r, {
        configurable: !1,
        enumerable: !0,
        get: e
    })
}, t.n = function(n) {
    var r = n && n.__esModule ? function() {
        return n.default
    } : function() {
        return n
    };
    return t.d(r, "a", r), r
}, t.o = function(n, t) {
    return Object.prototype.hasOwnProperty.call(n, t)
}, t.p = "", t(t.s = 3)
}([function(n, t) {}, function(n, t) {}, function(n, t) {}, function(n, t, r) {
r(0), r(1), n.exports = r(2)
}]);



via Mav

Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatRecordsList() must be of the type array, null given

I'm getting this error on Laravel 5.4. I'm creating tags for my blog but the only thing I get is an error.

public function category()
{
    return $this->belongsTo('gamstec\Category');
}

public function tags()
{
    return $this->belongsToMany('gamstec\Tag');
}

This is my Tag Model:

public function Posts()
{
    return $this->belongsToMany('gamstec\Post');
}

Now this is my PostController.php:

public function create()
{
    $categories = Category::all();
    $tags = Tag::all();
    return view('posts.create')->withCategories($categories)->withTags($tags);
}

The store Functions:

public function store(Request $request)
{

    // validate the data
    $this->validate($request, array(
    'title'         =>      'required|max:255',
    'slug'          =>      'required|alpha_dash|min:5|max:255|unique:posts,slug',
    'body'          =>      'required',
    'stickers'      =>      'required|min:1|max:20',
    'category_id'   =>      'required|integer',
    'postimg'       =>      'required'
));

    // store in database
    $post = new Post;

    $post->title        =       $request->title;
    $post->slug         =       $request->slug;
    $post->body         =       $request->body;
    $post->stickers     =       $request->stickers;
    $post->category_id  =       $request->category_id;
    $tags               =       $request->input('tags', []);
    $post->postimg      =       $request->postimg;

    $post->save();

    $post->tags()->sync($request->tags, false);

    Session::flash('success', 'La publicación se ha creado correctamente');

    // redirect to another page
    return redirect()->route('posts.show', $post->id);
}

This is the Tags crate form:

I'd tryied removing

$tags =  $request->input('tags', []);

and the same error.

This is my Tags Crete select form:






<select class="form-control select2-multi" name="tags[]" multiple="multiple">




@foreach($tags as $tag)




<option value=''></option>



@endforeach



</select>

so on select form i put the name="tags[]" with an empty array to pass the data into an array but still not working.



via Juan Rincón

Event Broadcasting Does not working json token web by authencatio not have request()->user()

I use JWT "json - web - token" for authentication and it does not save request () -> user () when I work with Authorizing Presence Channels always returns an error status 403 code in Route :: auth by code check:

 if(!$Request->user ()) {
   Throw new HttpException (403);

Authencation jwt of me not has request->user();

How can I modify this code from the outside like

If (JWTAuth :: guard ("member") -> user ()

Please help !



via Tran Hoang Hiep

Continue PHP Operation After User Exits Early

I'm using Laravel, PHP7, PHP-FPM, APCu and NGINX.

I have an HTML form where a user can upload a file, it connects to Upload.php.

File Process:

  1. validate
  2. name
  3. create thumbnail
  4. move from /tmp to /media
  5. create database record

Once the PHP script reaches a certain point, how can I have it continue running even if the user exits the upload page early? Or else a rogue file will be left in the directory without a database entry.

// Move uploaded file from /tmp to /media
Input::file('file')->move("/var/www/mysite/media", $image);

// Continue even if user exits early
// prevent a file in /media from not having a database record

// Thumbnail creation and other operations here
// May take several seconds

// Save database record
$image = new Gallery();
$image->name = $name;
$image->created_at = $date;
$image->save();

Should I use ignore_user_abort(true) and wrap the operations in a while(true)?

I have other bools in the script such as $upload = true. How does the while(true) know to represent ignore_user_about(true) and not another bool I have set?



via Matt McManis

Developing Nativescript app with Local API

This may be a silly question and I am very new to NativeScript. I have a sample project up. Trying to do a simple get request to a local api. This is a website setup on my local dev machine for:

http://test-api.dev/api/v1

I am trying to access an endpoint on my local API and it does not seem to return ANYTHING. But I can change the API endpoint to something that is not a local API and sometimes it return stuff.

The API is a Laravel/PHP api and I can confirm it is infact returning valid json, so I don't think the API is the problem. Here is my file.

var config = require("../../shared/config");
var fetchModule = require("fetch");
//var http = require("http");
var ObservableArray = require("data/observable-array").ObservableArray;

function GroceryListViewModel(items) {
    var viewModel = new ObservableArray(items);
    viewModel.load = function() {
        // http.getJSON(config.apiUrl + "events").then(function(result) {
        //  console.log(JSON.stringify(result));
        // }, function(error) {
        //  console.error(JSON.stringify(error));
        // });

        return fetch(config.apiUrl + "events", {
                headers: {
                    //"Authorization": "Bearer " + config.token
                    "Content-Type": "application/json"
                }
            })
            .then(handleErrors)
            .then(function(response) {
                console.log(response);
                return response.json();
            }).then(function(data) {
                console.dump(data);
                data.forEach(function(event) {
                    viewModel.push({
                        name: event.name,
                        id: event.id
                    });
                });
            });
    };

    viewModel.empty = function() {

        while (viewModel.length) {
            viewModel.pop();
        }
    };
    return viewModel;
}

function handleErrors(response) {
    if (!response.ok) {
        console.log(JSON.stringify(response));
        throw Error(response.statusText);
    }
    return response;
}

module.exports = GroceryListViewModel;

Please go easy on me, definitely seeking help on this though. Thank you all in advance.



via devcflynn

Dropzone.js post request in laravel 5.4

I am not receiving any request at controller's uploadGallery method. Although, the post request is received correctly.

gallery.blade.php

<div class="row">
    <form action="" method="post" class="dropzone" id="my-awesome-dropzone">
                            
                            <div class="dz-message">
                                <h3>Drop images here or click to upload.</h3>
                            </div>
                        </form>
                    </div>
    <script type="text/javascript">

        $(function (){

            Dropzone.options.myAwesomeDropzone = {
                paramName: "files",
                uploadMultiple:true,
                maxFilesize:6,
                autoProcessQueue: true,
                uploadMultiple: true,
                addRemoveLinks: true,
                acceptedFiles: ".png, .jpg, .jpeg",
                dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",
                dictRemoveFile: "Remove",
                dictFileTooBig:"Image is bigger than 6MB",

                accept: function(file, done) {
                    console.log("Uploaded");
                    done();
                },

                init:function() {
                /*  var submitButton = document.querySelector('#submit-all')
                        myAwesomeDropzone = this;

                    submitButton.addEventListener("click", function(
                        myAwesomeDropzone.processQueue();
                    ));

                    this.on("addedfile", function(){
                        $('#submit-all').show();
                    });*/

                },  
                success: function(file,done){
                    console.log("All files done!");
                }
        }
        });
    </script>

web.php

Route::get('/gallery', 'PagesController@Gallery');
Route::post('/file-upload', 'ImagesController@uploadImages');

ImagesController.php

<?php

namespace App\Http\Controllers;

use App\User;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ImagesController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function uploadImages(Image $request) {
        $images = request()->file('files');
        dd($images);
        return view('Gallery');
    }
}

Anything inside the uploadImages function is not running. Why?



via Mayank_17

Laravel: Changing elements on textbox edit

First Laravel Project. I want to make a form where if I write something in a textbock (for example a barcode) the code searches in a database and prints out a value (for example the price)

My code is so far:

The view:


<script>
function showProduct(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","script/getproduct.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>

//If I don't set the @vars first I get "unknown variable" error
<?php $name=0; $price=0; ?>
<table>
<tr>
<td></td>
<td><div id="txtHint">Name: </div></td>
<td><div id="txtHint">Price: </div></td>
</tr>
</table>


The showproduct.php:

<?php
$q = intval($_GET['q']);

$sql = DB::select('select * from inventory where barcode = ? LIMIT 1', [$q]);

$price = $sql[0]->price;
$name = $sql[0]->name;
?>

But when I put a barcode to the textfield I still got 0 in the fields. What I did wrong?



via Feralheart

laravel mailables -> replace tokens after view rendered

following thing:

I read posts from a wordpress database. The idea is that the posts act as master.

E.g. we have a wordpress post with post content:

Hi XX_USERNAME_XX,

nice to meet you.

XX_LARAVEL_CONTENT_XX

thanks for your donation of XX_DONATION_AMOUNT_XX

bye

I now want to send a normal laravel mailable that when sending out, does the replacements. Now the thing is the views in laravel typically act as master.

in this case though, I want the wordpress post content to be the master, and insert the laravel view into the wordpress content (XX_LARAVEL_CONTENT_XX). And while doing that, replace additional tokens (XX_DONATION_AMOUNT_XX).

How can I do stuff, just before the laravel mailable is rendered? e.g. before the output of the mailable is passed to the mail service, i want to hook in my own filter, take the output from the mailable and put that output into the wordpress post. Is there something supporting this?



via Toskan

Which files updated after composer update

I have added a new package to my project via composer. Now the project is on a shared hosting. After uploading only the package from Vendor folder, The project not working.

What are the other files should I upload to my hosting ?



via Marwan

Laravel 5.4 detecting variable in developing mode but not in production mode

I am learning laravel and for my practicing purpose I am working on a project. When that app run in local machine it work perfectly but in live server it doesn't. Whats wrong here? I know it's kind of weird but just cant figure it out.

Here is my view

@foreach($product_details as $product_detail)
    <div data-repeater-item class="mt-repeater-item">
        <div class="mt-repeater-row">
            <div class="col-md-2"></div>
            <div class="col-md-3">
                <label class="control-label">Title</label>
                <input type="hidden" name="indicator_id" value="">
                <input name="title" type="text" placeholder="Title" class="form-control" value="" /> </div>
            <div class="col-md-6">
                <label class="control-label">Description</label>
                <textarea name="description" type="text" placeholder="Description" class="form-control description content" ></textarea> </div>
            <div class="col-md-1">
                <a href="javascript:;" data-repeater-delete class="btn btn-danger mt-repeater-delete">
                    <i class="fa fa-close"></i>
                </a>
            </div>
        </div>
    </div>
@endforeach

Here is Controller

$product_details = IndicatorDetails::where('indicator_id',$id)->get();

return view('admin.indicator.indicator_edit')->with('product_details',$product_details);

And Model

class IndicatorDetails extends Model
{
    protected $fillable = ['title','description','indicator_id'];
    public function indicator()
    {
        return $this->belongsTo(Indicators::class);
    }
}

Thanks in advance.



via R.H.Prem

Laravel 5.2 macOs Sierra phpunit test not cannot find my button

I am trying to go to the home page and click on my button

 <a href="" id="createQuiz" class="crud-btn">createQuiz</a>

I made a test to do that

public function testExample()
    {
      $this->visit('/home')->click('createQuiz');
    }

However when I run the test with

phpunit --filter quizCreation "tests\quizCreation"

I get the error ...quizWhiz/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/Interac tsWithPages.php:464

InvalidArgumentException: Could not find a link with a body, name, or ID attribute of [createQuiz].



via GustX

Why can't I add a module using Laravel Angular Material Starter?

I am using Laravel 5 Angular Material Starter to develop a web app and I want to add this module to my angular application: https://github.com/arunisrael/angularjs-google-places.

To do so, I enter the command bower install angularjs-google-places --save in my terminal. Then, I add my ngGPlaces dependency to components in the file index.modules.js and do a gulp.

But when I want to access to this module, I get this error:

Failed to instantiate module app due to: [$injector:modulerr] Failed to instantiate module app.components due to: [$injector:modulerr] Failed to instantiate module ngGPlaces due to: [$injector:nomod] Module 'ngGPlaces' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I can't find what's wrong. Any ideas?



via LeGaulois88

Laravel - how to know if the attribute exists in relacional table

im doing a property sales website, and i have todo an advanced search, with number of bedroom for example.

but i have properties like shop that dont have bedroom attributes,how to know each table i have to search like apartment or house. i'm using scopes and for location and type of properties works fine.

My property model

public function atributos(){
        //se for moradia
        if ($this->tipoimovel_id == 1) {
            return $this->hasOne(Moradia::class);
        }
        //se for apartamento
        else if ($this->tipoimovel_id == 2) {            
            return $this->hasOne(Apartamento::class);
        }
        //se for loja
        else if ($this->tipoimovel_id == 3) {
            return $this->hasOne(Loja::class);
        }
        //se for armazem
        else if ($this->tipoimovel_id == 4) {
            return $this->hasOne(Armazem::class);
        }
        //se for terreno para construção
        else if ($this->tipoimovel_id == 5) {
            return $this->hasOne(TerrenoConstrucao::class);
        }
        // se for terreno para outros fins
        else if ($this->tipoimovel_id == 6) {
            return $this->hasOne(TerrenoOutrosFins::class);
        }
    }      

Warehouse dont have number of bedrooms

Schema::create('armazens', function (Blueprint $table) {
    $table->integer('imovel_id');           
    $table->integer('areaAcessoria');
    $table->integer('areaTotal');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

house have

Schema::create('moradias', function (Blueprint $table) {
    $table->integer('imovel_id');
    $table->integer('nrPisosConstrucao');
    $table->integer('nrQuartos');
    $table->integer('nrWcs');
    $table->integer('areaConstrucao');
    $table->integer('areaTerreno');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

My scope to search by number of bedrooms

public function scopeProcuraNrQuartos($query,$nrQuartos){
    if ($nrQuartos) $query->where( $this->atributos()->nrQuartos , '>=' , $nrQuartos);
} 

i know that its wrong, but exist some validation to know if that attribute exists in the table? Thanks



via D. Lopes

Laravel 5.3 - No break between lines in email?

I send an email out via the toMail channel, which is saved from a text area where I hit enter twice for new line, so it looks like this in the input:

Line 1

Line 2 with space above and below

Line 3

When I use that text in the mail like this:

return (new MailMessage)->subject('test spacing')
                        ->line($this->text);

It looks like this in the email:

Line 1 Line 2 with space above and below Line 3

I changed the relevant section in email.blade.php from:

@foreach ($introLines as $line)
  
@endforeach

To:

@foreach ($introLines as $line)
  {!! nl2br(htmlspecialchars($line)) !!}
@endforeach

But that still didn't work. In the notifications table in the db, it is saved as:

Line 1\n\nLine 2 with space above and below\n\nLine 3

Any idea how to get the sent email to show the spacing so it's not just one big blob?



via Wonka

Laravel Validation Rules If Value Exists in Another Field Array

I am working in Laravel 5.4 and I have a slightly specific validation rules need but I think this should be easily doable without having to extend the class. Just not sure how to make this work..

What I would like to do is to make the 'music_instrument' form field mandatory if program array contains 'Music'.

I found this thread How to set require if value is chosen in another multiple choice field in validation of laravel? but it is not a solution (because it never got resolved in the first place) and the reason it doesn't work is because the submitted array indexes aren't constant (not selected check boxes aren't considered in indexing the submission result...)

My case looks like this:

<form action="" method="post">
    <fieldset>

        <input name="program[]" value="Anthropology" type="checkbox">Anthropology
        <input name="program[]" value="Biology"      type="checkbox">Biology
        <input name="program[]" value="Chemistry"    type="checkbox">Chemistry
        <input name="program[]" value="Music"        type="checkbox">Music
        <input name="program[]" value="Philosophy"   type="checkbox">Philosophy
        <input name="program[]" value="Zombies"      type="checkbox">Zombies

        <input name="music_instrument" type="text" value"">

        <button type="submit">Submit</button>

    </fieldset>
</form>

If I select some of the options from the list of check boxes I can potentially have this result in my $request values

[program] => Array
    (
        [0] => Anthropology
        [1] => Biology
        [2] => Music
        [3] => Philosophy
    )

[music_instrument] => 'Guitar'

Looking at validation rules here: https://laravel.com/docs/5.4/validation#available-validation-rules I think something like his should work but i am literally getting nothing:

  $validator = Validator::make($request->all(),[
        'program'           => 'required',
        'music_instrument'  => 'required_if:program,in:Music'
  ]);

Thoughts? Suggestions?

Thank you!



via GRowing

jQuery post POST became GET

Strange situation

i send date with jQuery post

$.post('/headline/', {date : 'some content'});

But server header show that request is GET instead POST.

Local version works fine, but when upload to server then POST became GET

Other post requests works fine, just this one not working

P.s. backed is Laravel



via Fatas

Laravel user input form to query database

been trying to create a laravel form with several fields that the user can enter text/number into a field and it takes the field with data and performs a database query. Now the form works with just one field but when i add more fields it only returns data for the final query, not for the other two.

perfumes controller

class perfumescontroller extends Controller
{
  public function index()
 {
   $pstoreNum = request('pstoreNum');


   $result = perfumes::where('StoreNumber','=',$pstoreNum)
        ->get();

    return view('perfumes',compact('result'));


   }

   public function perfWeekSearch()
    {
   $weekNum = request('perfWeekNum');


   $result = perfumes::where('WeekNumber','=',$weekNum)
        ->get();

    return view('perfumes',compact('result'));


    }


    }

Route::get('/perfumes', 'perfumescontroller@index'); Route::get('/perfumes', 'perfumescontroller@perfWeekSearch');

Blade:

<form action="perfumes" method="get">
            
              <div class="input-group">
                <input type="text" class="form-control" name="perfWeekNum"                     placeholder="Type in Store Number"> 
                  <span class="input-group-btn"> 
                    <button type="submit" class="btn btn-default">
                      <span class="glyphicon glyphicon-search"></span>
                    </button>
                  </span>
              </div>
          </form>

Do i need to use some sort of check if not null method? or is there an easier way??

Thanks



via PA060

Customising token response Laravel Passport

I am working on an API at the moment and have hit a brick wall. I am using Passport with the 'Password' grant type.

I want to return the user information with the access tokens, however, I am not sure how to.

Which class could I implement, edit or extend to get this?.

I would like this to be returned:

{
    "token_type": "Bearer",
    "expires_in": 31536000,
    "access_token": "lalalalalal",
    "refresh_token": "lalalallala",
    "user": {
        "username": "a username",
        "user_type": "admin"
    }
}

Thanks in advance.



via Irvin Chan

Share API like facebook using PHP laravel

Hi I'm using PHP laravel for my social media application. I want to create one share API like FB so that users can post or share their info from their website. Can anyone suggest me idea or Pls share me link if it is already exist



via Nans Postpositives

How to display a text inside a tag if a value passed from controller is true using blade template?

I want to disable input if the value transferred from the controller is false. I read the blade template documentation for Laravel, but couldn't find any useful resource.

I tried the following code, but it yields an error.

<input type="text" name="url" style="height:36px;"   value="http://theurl.in/" @if $isEditable enabled @endif /> <br/>

The exact code part is,

@if $isEditable enabled @endif

enter image description here

If you can provide any suggestion, it would be very helpful.

Thanks!



via Isuru

different time in API response at first call and then call again?

I created an API in Laravel. When I first call the API in Postman it shows 504ms, then I call it again and it shows 235ms in Postman. If I call it once again it returns about 220ms to 280ms max?

If I stop making calls to the api for few minutes (about 10-15 min) when I call it again it takes around 500ms for the first time and then it shows near 200.

Is it cached data or persistence call or Zend opCache?

Can anybody help me find out why or what is this?



via Abhishek Badole

VirtualBox / Mac permissions error

I am running debian on my virtualbox on my Macbook Pro.

When building my Laravel application - I have set my permissions locally to be 777 on public, storage and bootstrap.

Every time I logout / in I then get another permissions error:

enter image description here

My mount permissions are:

sudo mount -t vboxsf -o auto,exec,rw,uid=1000,gid=33 BASE ./BASE

Can anyone advise what I need to do to fix this? I've tried sticky bit, but no joy.

Thanks



via Paolo Resteghini

How to Auto Inject Dependency with Laravel

I'm trying to build a structure that uses dependency injection on lumen.

I Have a Service Layer and repository layer.

I want to inject the repository layer to service layer. Let me try to show you the code

    interface IUserRepostitory {
        public function getByID($id);
    }

    class UserRepository extends BaseRepository implements IRepository{
        public function getByID($id) {
            //Please don't think how this function works, my question about dependency injection
            return $this->findOrFail($id);
        }

    }


   interface IService {
       public function getByID($id);
   }

   class UserService implements IService{

       private $Repository;
       public __construct(IUserRepositor $UserRepository) {
            $this->Repository = $UserRepository
       }

       public function getByID($id) {
             return $this->Repository->getByID($id);
       }
   }

Here I'm registering the dependency resolver.

//Dependency resolver for Repository Layer
class RepositoryServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserRepository::class, function () {
            return new UserRepository();
        });
    }

}

Here I'm registering Service Layer

class ServiceServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserService::class, function () {
            //Here is what I don't like
            //It would be great a solution that automaticly resolve UserRepository.
            return new UserService(new UserRepository());
        });
    }
}

As you see, I want to auto resolve the dependency into UserService. But singleton method need to create the returning object.

Is there a better way for this?

*** note : please don't pay attention on syntax, I'm writing it on lumen but the same problem on laravel.



via fobus

Laravel MongoDB Moloquent Pivot tables

I'm have document that will be shared to multiple users. Users will have different roles for each document. In sql, I would make pivot table with additional field 'role'. In mongodb, i'm unable to create relationship through pivot table. I don't want to save data about sharing in my mongodb object, be cause it isn't relative data. What are other options? Thank you.



via Karolis Tička

How to display SPECIFIC laravel validation error in view, not all of them

The problem I am having is I have multiple validation rules on my date of birth field.

        @if($errors->has('dob'))
            <span id="helpBlock" class="help-block error">
                @foreach($errors->get('dob') as $message) 
                    
                @endforeach
            </span>
            <script>$('#dob').addClass('formError');</script>
        @endif

This will print out ALL of the errors.

I only want to print out the 'required' validation rule if it gets triggered, I am handleing the other validation in the front end.



via gxrobb

Trying to hook into Model 'updating' event with a trait

I'm trying to provide a way to track when a user makes a change to a model for a notes section in my application. E.g. John goes and modifies 2 fields, a note would be created saying John has changed title from 'My title 1' to 'My title 2' and content from 'Lipsum' to 'Lipsum2'.

Here is a trait I created:

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait TrackChanges
{
    public $changes;

    public static function bootChangesTrait()
    {
        static::updating(function($model)
        {
            $this->changes = [];

            foreach($model->getDirty() as $key => $value)
            {
                $original = $model->getOriginal($key);

                 $this->changes[$key] = [
                    'old' => $original,
                    'new' => $value,
                ];
            }
        });
    }
}

And I am using that trait successfully on my model. However, I'm not sure how to capture the contents of the changes, or if they are even working correctly.

In my controller I have:

$site = Site::findOrFail($id);

// Catch and cast the is_active checkbox if it's been unselected
if ( ! $request->exists('is_active') )
{
    $request->request->add([ 'is_active' => 0 ]);
}

// // Get rid of the CSRF field & method
$data = $request->except([ '_token', '_method' ]);

$site->update($data);

I tried dd($site->changes) before and after $site->update($data); but it just returns null.

What am I doing wrong?



via Mark

Laravel 5.3 - Pull data of polymorphic table in one query?

Using the polymorphic relationship likeable, I have setup authors and books as likeable_type in likeable_items table.

Here are the models:

class Like extends Model {
    public function likeable(){
        return $this->morphTo();
    }
}

class Author extends Model {
    public function likes(){
        return $this->morphMany('App\Like', 'likeable');
    }
}

class Book extends Model {
    public function likes(){
        return $this->morphMany('App\Like', 'likeable');
    }
}

I want to use one efficient query to pull them both in with their respective data, paginated by 10, something like this does not work (I commented the code to show what is needed in each step).

$likeableData = 
DB::table('likeable_items')
  // We want to fetch additional data depending on likeable_type
  ->select(['books.title', 'books.author_name', 'book_counts.like_count']) // when likeable_type = 'book'
  ->select(['authors.name', 'authors.country', 'authors.age', 'author_counts.like_count']) // when likeable_type = 'author'
  ->leftJoin('books', 'books.id', '=', 'likeable_items.likeable_id') // when likeable_type = 'book'
  ->leftJoin('book_counts', 'book_counts.book_id', '=', 'likeable_items.likeable_id') // when likeable_type = 'book'
  ->leftJoin('author_counts', 'author_counts.author_id', '=', 'likeable_items.likeable_id') // when likeable_type = 'author'

  // We want to have distinct results, based on unique id of book/author
  ->distinct()

  // We want to order by the highest like_count, regardlress of likeable_type
  ->orderBy('book_counts.like_count', 'desc') // order by highest like_count when likeable_type = 'book'
  ->orderBy('author_counts.like_count', 'desc') // order by highest like_count when likeable_type = 'author_counts'

  // We want to paginate the mixed results
  ->paginate(10);

return $likeableData;

How can I get the mixed results back of the highest liked author/book by likes_count, with their respective data, paginated by 10?



via Wonka

STORYLINE ( SCORM) with laravel

Storyline ( SCORM /LMS ) , Who could help me to import files scorm or lms, connect it with in a database (Mysql) to insert data in a table and display SCORM content.

The input would be the scorm (for example /public_html/project_name/file_name). The output could be a directory named file_name with separate directories for images/, slides/, video/, tests/, lectures/, etc. in the case of tests, I'd need the output to clearly name the test and its associated answer key.



via Honey

Storing 2 same id of post table with different language into database

I'm building a multi language website. In this case just 2 languages, it's Indonesian and English using Laravel. I have posts table, it will store id of each post and post_translations table is to store local, title, and description of post. I got the problem when storing data into database. I don't have any idea how to store post without inc the id except I've added 2 same post with Indonesian and English.

This is the result (wrong)

posts table

id 
1
2

post_translations table

id  post_id  locale   title
1     1      en       fisrt post
2     2      id       post yang pertama

Expexted result

posts table

id 
1

post_translations table

id  post_id  locale   title
1     1      en       fisrt post
2     1      id       post yang pertama

PostController

  public function store(Request $request) {
    $this->validate($request, [
        'title' => 'required',
        'slug' => 'required',
        'content' => 'required'
    ]);

    $post = new Post;

    $post->title = $request->title;
    $post->slug = $request->slug;
    $post->content = $request->content;

    $post->save();
    return redirect()->route('post.index');
}



via lolagi

Add the number gotten from a db

I collected a data from a database and the data is base on o user id id, ie I select data from database table base on a user id. Now the selected result has some value (numbers) how do i check if that total sum of the number is equal to a certain amount. Am using Laravel 5.4 I query my db as follow

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

now i have a column called cash how do i get the total sum of the cash column. what is the code for that since the result is an object do i do a foreach loop

 foreach ($money as $key => $value) {
    count($money->cash);
   }

this will return the number count of the value

 foreach ($money as $key => $value) {
 echo $earn->earned_amount + $earn->earned_amount;  
   }

this will add up individual value to themselves. so please can anyone tell me how it is done.



via dagogodboss

Laravel Many-to-one relationship

I have two tables:

orders
-id
-status_id

status
-id
-label

Relations are:

Any Order has one status

public function status()
{
    return $this->hasOne('App\Status');
}

Any Status can belong to many orders

public function orders()
{
    return $this->belongsToMany('App\Order');
}

I suppose it is correct?

Now,if I use:

    $o = Status::with('orders')->get();

I get all the orders. If I use:

    $o = Order::with('status')->get();

I get an error! Column not found: 1054 Unknown column 'status.order_id' in 'where clause' (SQL: select * from status where status.order_id in (1, 2, 3, 4, 5)) But I don't have status.order_id, instead I have order.status_id.

How do I get the label of order's status? Like order->status->label?



via TheKitMurkit

onDelete('cascade') not deleting data on pivot table

I have the following migration:

 public function up()
    {
        Schema::create('youtube_topics_to_subscriptions', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->integer('topic_id')->unsigned()->index()->references('id')->on('youtube_topics')->onDelete('cascade');
            $table->integer('youtube_subscription_id')->unsigned()->index()->references('id')->on('youtube_subscriptions')->onDelete('cascade');
        });
    }

My undersatnding is that when using onDelete('cascade'), if I delete a subscription, then all associated YoutubeTopicsToSubscriptions will be delete.

When I run App\YoutubeSubscription::truncate(); all the subscriptions are deleted correctly from youtube_subscriptions table but no data is deleted from youtube_topics_to_subscriptions. what am I doing wrong?



via code511788465541441

tracking submissions by registered and anonymous users in laravel

I am using Laravel's pre-build Auth code. I have another table submissions which looks like this

Schema::create( 'submissions', function( Blueprint $table ) {
    $table->increments( 'id' );
    $table->enum( 'complete', [ 'yes', 'no' ] );
    $table->string( 'formName' );
    $table->timestamps();

    // Reference to User ID but only when submitted by a registered user...
    //$table->integer( 'user_id' )->unsigned();
    //$table->foreign( 'user_id' )->references( 'id' )->on( 'users' );

    $table->integer( 'status_id' )->unsigned();
    $table->foreign( 'status_id' )->references( 'id' )->on( 'status' );
});

When a submission is by a registered user I would like to reference that user id, But anonymous submissions are possible and I need some indicator that the submission is by an anonymous user.

should I?

  • creating an actual users records for an anon user
  • change my user_id foreign key to allow NULL values to indicate the anon user

or is there a better way?

EDIT: To expand on my use case

My application is basically a collection of forms( aren't they all ) for users to input and update information. Most of the forms will be restricted to Authenticated users. 2-5 forms will be available to both authenticated and non-authenticated users. IF the form submission is done by an Authenticated user I want to indicate to admins who that user is. If the user was not authenticated then I simply want to indicate to the admin that it was an anonymous submission. So Anon users wont require any logic, and this will simply be a flag to indicate the source of hte submission to Admins. That said it sounds like nullable() key on user_id may be the way to go.

Going forward I'm looking at adding tracking so if a submission is made by a user that becomes an authenticated user I can back track and update their submissions to indicate the user.

Thanks



via Nathan

Upload file with post in laravel phpunit test

In my test, I load an existing file and attempt to pass it as a parameter when making a local api call:

        $this->user = $this->getAuthenticatableUser();

        $path = __DIR__.'/assets/MOCK_DATA.csv';
        $name = str_random(8).'.csv';
        $file = new UploadedFile($path, $name, 'text/csv', filesize($path), null, true);

        $this->actingAs($this->user)
            ->withSession(['companyId' => $this->user->companyusers()->first()->companyId])
            ->post('/api/v2/addByCsv', [
                'CSVUpload' => $file
            ])
            ->see('test');

However, the controller does not receive the data as a file. Using request->input, I can return the location of the file as a string, but the current code is not executing because hasFile does not return true:

if($request->hasFile($this->csvFieldName)){
    $csvContents = file_get_contents($request->file($this->csvFieldName));

Why is this not working correctly, and how can I get laravel to realize that I am passing a file as one of the post parameters?



via Zach P

AWS Multicontainer Docker using PHP and NGinx to install Laravel

I'm trying to run Laravel in AWS Multicontainer Docker Environments.

I have followed the tutorial on http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker_ecstutorial.html to deploy a simple PHP application with nginx, and it worked. So I have removed all the files in the default php-app folder and installed Laravel and ran composer install locally, and deployed using eb deploy command. However, I received the following error message:

Warning: require(/var/www/html/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required '/var/www/html/bootstrap/../vendor/autoload.php' (include_path='.:/usr/local/lib/php') in /var/www/html/bootstrap/autoload.php on line 17



via Nucleus

Laravel 5.2 Update with foreign key

hello i've been working on a laravel project lately, and i've wanted to be able to update my records that have foreign keys in them. i've succesfully been able to update records in tables that dont have a foreign key but for some reason my table with a foreign key doesn't want to update. when i var_dump($voorraad) i get the new value on my screen but it doesn't update into the database. I have the same code for my Product table and Location table and there it works completely fine.

My Controller:

 public function update(Request $request, $id)
{
    //voorraad = stock in dutch
    //Product_id = foreign key from the table products
    //locatie_Id = foreign key from the tabe locations
    //aantal = ammount of a certain product

    $voorraad = Voorraad::FindOrFail($id);


    $voorraad->fill($request->only('aantal', 'Product_id', 'locatie_Id'));

    $voorraad->save();

    return redirect(route('voorraad.index'));

}

My Model:

protected $fillable = ['aantal', 'Product_id', 'locatie_Id'];

My edit form:

    {!! Form::model($voorraad,['action' => ['VoorraadsController@update', $voorraad->Id], 'method' => 'PATCH'])!!}

{!! Form::label('aantal', 'aantal:') !!}
{!! Form::text('aantal')!!}<br>

{!! Form::label('Product_id', 'product:') !!} 
{!! Form::select('Product_id', $products)!!}<br>

{!! Form::label('locatie_Id', 'locatie:') !!} 
{!! Form::select('locatie_Id', $locaties)!!} <br>

{!! Form::submit('edit') !!}

Gyazo of Var_dump($voorraad): https://gyazo.com/109d54e2bb7a91bbb8b047611e66dbe0

gyazo of var_dump($request):https://gyazo.com/8437ee90881ba38a039b5b583f8296a5

If there is any information missing just let me know and i'll add it



via B. All

Run two websites with one laravel installation

How we can use multiple applications with one Laravel installation.

For example: www.apple.com www.orange.com

both website will use ONE CORE laravel installation with separate database and all other separate stuff.

Is that possible? If yes then how?

Also I have done the same thing for CodeIgniter but not sure how i can do with laravel.



via Danial Butt

Database (database/database.sqlite) does not exist. Database works from artisan tinker

I created my database.sqlite file in the database folder. My .env file contents are :

DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database/database.sqlite
DB_USERNAME=
DB_PASSWORD=

When I run php artisan tinker and DB::table('users')->get(); I get the info from the database.

My DatabaseController is:

class DatabaseController extends Controller
{
    public function main()
    {
        $users = DB::table('users')->get();

        return view('database',compact($users));
    }
}

Yet when I request /database path I get the error:

QueryException in Connection.php line 647: Database (database/database.sqlite) does not exist. (SQL: select * from "users")



via Alexandru Antochi

Laravel output single row from database

I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website. I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();


    return redirect()->route('texts.index');
}


/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}

}

I would think that I am missing something in the MainController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;


class MainController extends Controller
{
public function index(){

    return view('index');
}

Could that be?

Thanks in advance!



via Camilla Holst

How to force int to string in Laravel JSON?

I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...

I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.

Is there a way to somehow force response()->json() to return int's as string's?



via Duvdevan

Calculated fields in Laravel using Query Builder

I've been working in a Laravel Project and I want to know how can I show a calculated field in a blade view? I want to retrieve some information from an invoice and a Total calculated field.

I would like to get this result, but using Eloquent ORM. The query is this:

SELECT 
    invoiceheader.id, 
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname, 
    invoiceheader.customernit,
    invoicedetail.productid, 
    invoicedetail.quantity,
    invoicedetail.saleprice, 
    (quantity * saleprice) as Total
FROM invoiceheader 
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid

Thank you so much in advance.



via krlosfgx

How can I optimise this eloquent query to remove duplicates

I have this query in my controller, which produces a result I send to Datatables.

    $query = Appointment::with(['agent', 'instruction_type', 'sign_up_customer']);
                $query->with(['statuses' => function ($query) {
                    $query->latest()->first();
                }]);
                $query->paginate(10);
$table = Datatables::of($query);

But it is producing this query with 9 duplicate statements. How can I optimise this query to remove the duplicates?

select count(*) as aggregate from `appointments`
select * from `appointments` limit 10 offset 0
select * from `agents` where `agents`.`id` in ('1')
select * from `instruction_types` where `instruction_types`.`id` in ('1')
select * from `organisations` where `organisations`.`id` in ('2')
select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc     select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at`, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1
select count(*) as aggregate from (select '1' as `row_count` from `appointments` limit 10 offset 0) count_row_table
select * from `appointments` limit 100 offset 0
select * from `agents` where `agents`.`id` in ('1')
select * from `instruction_types` where `instruction_types`.`id` in ('1')
select * from `organisations` where `organisations`.`id` in ('2')
select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1
select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at`, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1



via showFocus

Laravel pass ID back from controller to view via redirect with errors

How can I pass $id back from controller to the same view when update is failed and error is trigerred.

I have view which prints all items from database and also adds edit button to each of the items which triggers modal popup window.

@for ($i =0; $i < count($inventory); $i++)

                     <tr>

                       <td>  </td>
                        <td>
                        <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
                          Edit
                        </button>

After editting all the data are passed to route via form

<form action="/updateInventory/" method="post">

Then it goes to my controller which validates input and then inserts input into database.

public function update(Request $req,$id)

{
    $this->validate($req, [
        'name'=> 'min:2'
        ]);
    $inventory = inventory::find($id);
    $inventory->name = $req->input('name');
    $response = $inventory->save();


    if($response)
    {
        return redirect()->back()->with(['message'=>'gerai']);
    }


    return redirect()->back()->withErrors(['error'=>'negerai']);
    //return redirect('/inventory');

}

But if input doesn't pass validation I'm printing error like that.

@include ('partials.notice')

                    @if($errors->any())

                    <script>
                        $(function() {
                            $('#myModal').modal('show');
                        });
                        </script>
                    @endif

How can I pass $id of element I just edited from controller back to the same view so when @if($errors->any()) triggers I can popup my modal $('#myModal').modal('show'); with element I wanted to edit.



via Benas Gasiūnas

Calculate sum of dynamically adding input fields with jquery

I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

This code is calculating sum of rendered rows not the new created rows

 $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));


        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        }); 
});

enter image description here



via Rizwan Saleem

Laravel sessions; Are they cached from when a method is first called?

I have two methods that are called via ajax: The slow one that is called first (sleep is just used to illustrate a method that takes longer to return):

sleep(10);
return Session::get('bucket');

The second one that is called and finishes before the above method:

Session::push('bucket', 'Test');
return Session::get('bucket');

The second one returns the bucket with 'test' in it but when the slow one finishes it returns nothing because it thinks the array is empty even though the second method added something to it.

So is the session cached from when a controller method is first called? It seems like it but I'm not sure.

Cheers!



via BarryWalsh

Laravel preview and download of uploaded file/image

I would like to develop a page in which the user can associate (upload) a file (img, pdf, csv ...) to a database record and then having a preview of the file (image or icon) and download it with a click. I think it is a very common scenario but despite of the good laravel documentation and although I found some similar questions (this, this and this) I can't figure it out.

I successfully upload the file (and store the name in the database) with: - the blade view

<form action=""
      method="post" enctype="multipart/form-data">
  
  <input type="file" name="order_file" 
  <input type="submit" title="Upload"> Upload
</form>

  • and the controller

    public function uploadfile (Request $request, Order $order) {
    
      $this->validate($request, ['order_file' => 'image|mimes:jpeg,bmp,png|max:2000']);
      $filename = $request->file('order_file')->storeAs('orders',$request->file('order_file')->getClientOriginalName());
      $order->order_file = $filename;
      $order->save();
      return redirect()->route('orders.edit',['id'=>$order->id])->with(['flash_message' => 'Order file successfully uploaded (delay).']);
    }
    
    

In the view I add this part to show different URLS

<ul>
    <li> Order file :  </li>
    <li> URL order file :  </li>
    <li> Asset :  </li>
    <li> Storage URL :  </li>
    <li> <img src="????"> </li>
    <li> <a href="????">Download</a> </li>
  </ul>

The result is

but I do not understand the right way to complete



via AlexMI

Faking logins with Laravel Auth

On our service there's admins and other users. I'm using the basic Laravel Auth package for handling registrations, logins etc.

What would be the best way to implement a feature, where an admin user could "fake login" as a regular user, without knowing the actual user's password?



via Apeli

Session doesn't save value with redirect-> "with" method laravel 5.2

When I put data like this:

$request->session()->put('123', '12345')

, session contains this value, but when I try to put data into session this way

$result = ['status' => 'Product has been updated']
return redirect('/admin/products/')->with($result);

Session doesn't contains it.

kernel:

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
         \Illuminate\Session\Middleware\StartSession::class,
         \Illuminate\View\Middleware\ShareErrorsFromSession::class
    ];

routes:

Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
    Route::get('/', ['uses' => 'Admin\IndexController@index', 'as' => 'adminIndex']);
    Route::resource('/products', 'Admin\ProductController');
});

I have red about changes in laravel 5.2 and that this problem may cause web middleware but i haven't it in my routes. Why session doesn't contain given status then?



via Batmannn

Change date format in datatable using Laravel and Symfony

I'm trying to change the format of a date field in the DataTable, so not in the form! These fields are created using the formbuilder Symfony. I have no clue how to do this, or were to place it. I Have tried to change the format of the date in DateForm.php but that doesn't change the data in the datatable. I hope this is enough code to understand the situation, else just tell me.

My datatable DateTable.php

class DateTable extends BaseDataTable{
    use FilterableDataTableTrait;
    public function ajax()
    {
        $view = view('admin::crud.actions');

        $query = $this->query();

        return $this->datatables
            ->eloquent($query)
            ->addColumn('id', function ($item) {
                return $item->id;
            })->addColumn('action', function ($item) use ($view) {
                $view = $item->relation ? view('admin::date.actions') : view('admin::date.actions');
                $view->with('item', $item);
                return $view->render();
            })->make(true);
    }

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())

            ->addAction(['title' => '', 'width' => '100px'])
            ->ajax('')
            ->parameters(array_merge($this->getBuilderParameters(), ['autoWidth' => false]));
    }
 }

My form DateForm.php:

class DateForm extends AbstractType{
private $data;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $this->data = $builder->getData();
    return $builder
        ->add('date', 'date',
            [
                'required' => true,
            ])
        ->add('description', 'textarea', ['required' => true
        ]);
}
}



via Koen van de Sande

What is better: long polling or websockets?

I write laravel application with realtime notificatons.

Currently all updates come through websocket, but as I see some big websites still use long-polling technique for realtime updates.

Which one to prefer?



via Jackson J

Chain whereHas to traverse through a self-referencing model

Using Laravel 5.4....

Imagine I have the following models:

App\Location

This has a self referencing hierarchy, and has the following data

UK
  |---North West
  |             |----Liverpool
  |             |----Manchester
  |---North East
                |----Newcastle
                |----Sunderland

In this model I have a self relation

public function parent()
{
    return $this->belongsTo('App\Location', 'location_id');
}

and a recursive relation...

public function parentRecursive()
{
   return $this->parent()->with('parentRecursive');
}

App\Shop

The shop model has a 'location' relation.

public function location()
{
    return $this->belongsTo('App\Location', 'location_id');
}

What I want to do is to get all of the shops within a category. So if I have a shop called "ACME" that is related to "Liverpool", I can easily get it by sending the ID for "Liverpool" (as $value) in the following condition....

->whereHas('location', function($q) use ($value) {
        $q->where('id', $value);
})

But technically, this shop is also in "North West" and in "UK".

So if I send the ID for the UK Location to that query, it will not return the ACME shop as it is not directly related to North West or UK ID.

I can get it working by sending the UK id ($value) to this...

$this->builder->whereHas('location', function($q) use ($value) {
    $q->where('id', $value);
})->orWhereHas('location.parent', function($q) use ($value) {
        $q->where('id', $value);
})->orWhereHas('location.parent.parent', function($q) use ($value) {
        $q->where('id', $value);
});

So is there a better way to write the above which is ugly and would only work for a finite number of 'jumps' in the relation tree? I need it to traverse all of the locations until it reaches the top of the tree.



via Bazlid

Laravel - method merge

I did a method to filter the results, I want for example looking for a hotel in a city and whose price and between 0 and 49, I have 4 checkbox 0-49, 50-99,100-149,150-200 I want If I click on the first it gives me the names of the hotels whose city given in query and the price that is in the value of checkbox

For example:

If I look for the city Casablanca, it gives me the name of the hotels that have in Casablanca and when I click on the checkbox 0-49 it gives me the hotels that have in Casablanca and whose price is between 0 and 49 and so on For other checkboxes when I click on the first checkbox that contains the value 0-49 and the second one that contains the value 50-99, it gives me the hotels that have in Casablanca and whose price is between 0 and 49 and 50 -99 and so on

The method works very well, the problem is in pagination, when I click on a single checkbox it gives the exact page number and the number of element to display in the pages is 25

$ Perpage = 25;

I have made $ product to display the names of hotels and $ afica to calculate the total number of results, because the method "totalHits ()" only works with the get () method,

$ Books = $ product [0]; // this line stores the first results that is to say when I have a single checkbox but when I click on several checkbox it enters the loop for:

for($i=1;$i<count($product);$i++){

            $collection  = new Collection();
            $collection2 = new Collection();

            $collection= $product[$i];

            $nbPages = floor($res/$perpage);

            $books = $collection2->merge($books)->merge($collection);

            }

My problem is:

When I did the merge method to combine the two results it is to say:

$ Books = $ product [0]; And $ collection = $ product [$ i]; $ Books = $ collection2-> merge ($ books) -> merge ($ collection); It is the only method that worked with me but the problem is that I want to show 25 elements per page, it shows me the 25 elements of the first results and 25 of the second is you say Example $ books = $ product [0]; And $ books = $ product [1]; And that he gives me another page in the pagination that is empty, because the results that had to be displayed in the empty page it has to display in the first page.

For example, if the total number of the first results is $ books = $ product [0]; It gives me 42 element, and $ collection = $ product [$ i = 1]; Gives me 87 so the page number is 129/25 it gives me 5 page, it shows me in a first page 50 element and so follows what it does in the 5th page is empty because it displayed in The other page

How to solve this problem?

I use Elasticsearch and Laravel.

My function :

public function pricefilter(Request $request)
{
    $query = Input::get('query', false);
    $brans = request()->priceFilter;
    $perpage = 25;

    if ($query = Input::get('query', false))  {  

        foreach ($brans as $data) 
        {

            $minMax    = explode("-",$data);
                $product[] = Afica::search()
                                 ->multiMatch(['name','city_hotel'], $query, ['fuzziness' => 'AUTO'])
                                 ->filter()
                                 ->range('minrate',['from'=>$minMax[0],'to'=>$minMax[1]])
                                 ->paginate($perpage)
                                 ->appends('priceFilter' , request('priceFilter'));

                 $afica[] = Afica::search()
                                 ->multiMatch(['name','city_hotel'], $query, ['fuzziness' => 'AUTO'])
                                 ->filter()
                                 ->range('minrate',['from'=>$minMax[0],'to'=>$minMax[1]])
                                 ->get();     

        }


        $books = $product[0];
        $af = $afica[0];
        $res = $af->totalHits();
        $nbPages = ceil($res/$perpage);
        $kaa = new Collection();

        for($i=0;$i<count($afica);$i++)
        {  

            $cole =  $afica[$i];
            $cole = $cole->totalHits();
            $ka = $kaa->push($cole);
        }                    

        $res = $ka->sum();

        for($i=1;$i<count($product);$i++){

            $collection  = new Collection();
            $collection2 = new Collection();

            $collection= $product[$i];

            $nbPages = floor($res/$perpage);

            $books = $collection2->merge($books)->merge($collection);

            }

   } else {
        $books = Afica::search()
                 ->paginate(26);
   }

   if ($request->ajax()) {
       return view('presult2', compact('books','nbPages','pageActuelle','brans'));
   }

   return view('welcome2',compact('books','nbPages','pageActuelle','brans')); 
}

my view :

@foreach($books as $key => $value)

            <article class="one-third">
              <figure><a href="#" title=""><img src="" alt="" style="height: 215px!important;" /></a></figure>

              <div class="details">

                <h3>
                  <span class="stars"> 
                    <i class="material-icons">&#xE838;</i>
                    <i class="material-icons">&#xE838;</i>
                    <i class="material-icons">&#xE838;</i>
                    <i class="material-icons">&#xE838;</i>
                  </span>
                </h3>
                <span class="address">,  <a href="hotel?query=">Show on map</a></span>
                <span class="rating"></span>
                <span class="price">Max rate  <em>$ </em> </span>
                <span class="price">Min rate  <em>$ </em> </span>
                <div class="description">
                  <p><a href="hotel.html">More info</a></p>
                </div>   
                <a href="" title="Book now" class="gradient-button">Book now</a>
              </div>
            </article>

            <!--//deal-->
            @endforeach

<!--//bottom navigation-->
 <input type="hidden" id="nbPages" value="<?php echo $nbPages;?>">
            <div class="bottom-nav">
            <a href="#" class="scroll-to-top" title="Back up">Back up</a> 
            <div id="pager">
            <?php $query=Input::get('query', '');?>
            @if($query == "")
          <span><a href="?page=1">First Page</a></span>
            @else
         <span><a href="?query=<?php echo $query?>&page=1"=>FirstPage</a></span>
         @endif

<?php


$query = Input::get('query', '');

for($i=1; $i<=$nbPages; $i++) //On fait notre boucle
{
    echo '<span><a href="&page='.$i.'">'.$i.'</a></span>';    
}

?>


       @if($query == "")
          <span><a href="">Last Page</a></span>
            @else
         <span><a href="">Last Page</a></span>
         @endif
            <!--bottom navigation-->
              </div>
         </div>    
            <!--//bottom navigation-->



via koora et film Tv

which method is better to store meta-data (keywords and description) in Mysql (Laravel)?

There are "Articles", "News" tables. I want to allow admin to add meta tags like keywords and description when creating new articles or news. I have used laravel Polymorphic Relations and have two methods in mind to implement :

Method 1

meta_data Table:

id   metable_type   metable_id    meta_type      meta_content

1    news           4             description    php is a good...
2    articles       7             keywords       laravel,relation,tag
3    articles       2             keywords       php,developer,html

.

Method 2

meta_data Table:

id   metable_type   metable_id    meta_type      meta_content

1    news           4             description    php is a good...
2    articles       7             keyword        laravel
2    articles       7             keyword        relation
2    articles       7             keyword        tag
3    articles       2             keyword       php
3    articles       2             keyword       developer
3    articles       2             keyword       html

My Questions:

Is there a better approach than these two methods ? Which method is better?

User should be able to edit kewwords and descriptions for and article or news.



via Ahmad Mobaraki

Get the last record in a belongsToMany association

I have a belongsToMany association between Appointment and Status models. The below query returns all of the statuses and I want to alter it to pull the last status assigned to the appointment.

$query = Appointment::query();
            $query->with('statuses');
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);

I have tried altering the query with this but it doesn't work.

$query->with('statuses')->latest();

This is my raw query:

select * from `users` where `users`.`id` = '1' limit 1
select count(*) as aggregate from (select '1' as `row_count` from `appointments`) count_row_table

select * from `appointments` limit 100 offset 0

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc

select * from `agents` where `agents`.`id` in ('1')

select * from `instruction_types` where `instruction_types`.`id` in ('1')

select * from `organisations` where `organisations`.`id` in ('1')

So this works, but it runs two queries on Statuses

$query = Appointment::with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);



via showFocus

Advertisement