mardi 28 février 2017

how to get correct rank with infinite scroll?

Im getting video's rank according to net votes. im getting the correct results like this

id     | net_votes| rank
------ | -------: |:----:
2      |    11    |   1
4      |    6     |   2
1      |    5     |   3
5      |    5     |   4
3      |    3     |   5

Due to lots of videos and avoid loading issue, I tried to use infinite scroll. when I use infinite scroll first 5 videos shows correct rank, when I scroll down loading another 5 videos and rank shows as 1-5 (wrong rank). rank is checking for those 5 videos. I need to get continuous rank when I scroll. anyone can help me on this?

here is my code

    $subquery = "(
             SELECT    username,
                       net_votes,
                       contest_portfolio.id,
                       video,
                       portfolio_id,
                       Sum(net_votes) AS total,
             FROM      contest_portfolio
             LEFT JOIN portfolio
             ON        contest_portfolio.portfolio_id = portfolio.id
             LEFT JOIN users
             ON        portfolio.user_id = users.id
             LEFT JOIN profile
             ON        users.id = profile.user_id
             WHERE     contest_portfolio.status
             GROUP BY  contest_portfolio.id
             ORDER BY  total DESC,
                       contest_portfolio.created_at DESC ) totals,
                       (SELECT @r:=0) rank";

        $posts = DB::table(DB::raw($subquery))
            ->select(
                '*',
                'total',
                DB::raw('@r:=@r+1 as rank'),
                DB::raw('@l:=total'))
            ->paginate('5');

if ($request->ajax()) {
    $view = view('site.data',compact('posts'))->render();
    return response()->json(['html'=>$view]);
}

return view('my-post',compact('posts'));



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

i want to display return data to convert json

these my table database in the model sub_bidang

id  id_bidang       name    
1      1            Backend Developer   
2      1            Frontend Developer  
3      2            Senior Marketing

i want to display all the name in the array nama sub bidang by field id bidang

$data = Posting::find($id);

    foreach ($data->sub_bidang as $value) {

        $data = [

            'id posting job' => $data->id_posting_job,
            'id kategori' => $data->id_kategori,
            'nama kategori' => $data->kategori_posting['nama'],
            'id bidang' => $data->id_bidang,
            'nama bidang' => $data->bidang['nama'],
            'nama sub bidang' => [
                'bidang' => $value->nama
            ]  
        ]; 

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

but doesnt work, just display backend developer in the array nama sub bidang. like this

{
  "id posting job": 1,
  "id kategori": 1,
  "nama kategori": "Part Time",
  "id bidang": 1,
  "nama bidang": "IT",
  "nama sub bidang": {
    "bidang": "Backend Developer"
  }
}

there should be display backend developer and frontend developer, what the problem ?



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

Laravel 5 Search Not Working as expected

I`m new to the Laravel 5.4.i wanted to developed search when i enter id number need to fetch service from the database called new.but according to this code it is not functioning.it just show all the services without the exact value related to its id.All i want is if i enter id 1 ..i need to fetch out service related to id=1 and display it in search.blade.phpplease help me!

Here Is my Search.blade.php

 <!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="http://ift.tt/2dHeAcp" rel="stylesheet" type="text/css">

        <!-- Styles -->

    </head>
    <body>
       <form action="search" method="post">
       <label>Search by Id!</label><br>
       <input type="text" name="Search" /><br>
       <input type="hidden" value="" name="_token" />
       <input type="submit" name="submit" value="Search">
       </form>



        <table class="table table-bordered table-hover" >

            <thead>
                <th>Name</th>
            </thead>
            <tbody>
                @foreach($customers as $customer)

                    <td></td>

                @endforeach
            </tbody>   
        </table>

    </body>
</html>

Here is my Controller UserController

public function search_code(Request $request){

    $query = $request->search;
    $customers = DB::table('news')->where('id', 'LIKE',"%$query%")->get();
     return view('search' , compact('search', 'customers'));

    }

Here Is My Route

Route::post('search', 'UserController@search_code');



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

Laravel Pivot Table - How to increment third field with counter?

Hi guys wondering if you can help figure out what this eloquent statement should look like. It's pretty challenging, at least for me, but maybe not for some of you guys? Here is the scenario:

I have a pivot table with post_id and user_id and an additional column called "total_views" in the pivot table.

Basically what I'm trying to do is increment the views each time the user goes and view that specific post.

This is what the SQL would look like:

UPDATE post_user SET total_views = total_views+1 WHERE user_id=1 AND post_id=2

How would you write this in an eloquent statement? Big thanks for the first that can come up with a solution!



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

Avoid executing external plugins' test cases

composer.json

    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/socialite": "^3.0",
        ...
        "chencha/share": "^5.2"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7"
    },
    ...
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },

phpunit.xml

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory suffix="Test.php">./tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>
</phpunit>

When I run phpunit it gives me following error

PHP Fatal error: Class 'Orchestra\Testbench\TestCase' not found in /usr/lib/php5/voice/v1.5/vendor/chencha/share/tests/TestCase.php on line 3

I can add "orchestra/testbench": "~3.0" under my require-dev which will solve the issue, But is there way I can run only my test cases without the plugins' test cases?



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

MySQL columns json vs joins

I am stuck with database design of holiday package inventory project which contains a main table packages for storing package information.

Here is the fields

  1. id PK
  2. package_name varchar
  3. attractions json eg-field: ['super','funny'],
  4. inclusions json eg-field: ['hello','cool']

One package may have many attractions and inclusions so that's why i choose a json field.

So is this a slandered way or keep the attractions and inclusions in another table with foreign key relation??.

if i choose second method(ie different tables for attractions and inclusions) what about searching a package with particular attraction think that search requires a join query (Search with join is a bad practice??.).

But in the first method we can apply a json search (MySQL-version >5.7 supports json search).



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

I want to setup posts and taxonomy structure like WordPress using laravel eloquent model

Wordpress has these tables - Wordpress Posts and Taxonomy DB Structure

I have set up the posts and categories like this in the database, now how can I implement this relation using laravel eloquent model?

I have tried some ways, but not getting the idea clearly.



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

formData passed through ajax is not being available in Laravel

here is my form:

<form role="form" action="" method="post" enctype="multipart/form-data">
        Select an excel file to upload:
        <input type="file" name="fileToUpload" id="fileToUpload" multiple>
        <input type="submit" value="upload" name="submit">
        
</form>

the js code :

$('#fileToUpload').on('change',function(e){

                 var myFile = e.target.files[0];
                 var f_data = new FormData(); 
                 f_data.append('file', myFile);

                 $.ajax({
                    type : 'get',
                    data : f_data,
                    dataType : 'JSON',
                    url : "",
                    processData: false,
                    contentType: false,

                 }).done(function(data){
                    console.log(data);
                 });
});

here is the route ajax call is being made to:

Route::get('/ex2','ExcelController@ajax')->name('excel.form.ajax');

my code in the Laravel ExcelController file :

public function ajax(Request $r)
{
    return ['all_data' => $r->all(), 
            'request_files' => $r->allFiles(), 
            '$_FILES' => $_FILES, 
            'valid' => $r->file('file')->isValid()
           ];
}

............. now from the controller method, when i return the array with the "valid" key, the output is an object with bunch of empty arrays. but i do get a return at least.

but when i add the

'valid' => $r->file('file')->isValid()

in the array to be returned, as shown in the code above,the return is an internal server error, this :

GET http://localhost/larajects/ghureBerai02/public/ex2?[object%20FormData] 500 (Internal Server Error)

which i think is happening because isValid() method is being called on empty. which means the formData was not passed for some reason.

even the

if($r->all()) 

returns false

can anybody please tell me what could the reason be for this problem?



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

Laravel scheduled task route helper

I have a few views in Laravel for sending e-mails. In those views, I often use the route helper provided by Laravel. This function replaces the route name by the URL of the route.

This works great, until I want to send the same e-mails from a scheduled task via

php artisan schedule:run

Then it keeps saying the route cannot be found. But as I said, the same code works great when I run it in a browser.

The e-mail part isn't important in the issue, I only mention it as a reason for wanting to use the route helper in a scheduled task. The issue is with the route helper that doesn't work when used in a scheduled task.



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

Laravel scheduled tasks run with every migration

I'm trying to send an e-mail to members on their birthday in my website, created in Laravel. "Scheduled Tasks" seem to be the way to do this in Laravel, so I followed the instructions in their docs and added a call to my function in App\Console\Kernel.php like this:

protected function schedule(Schedule $schedule)
{
    $schedule->call($this->birthdayVouchers())->daily();
}

To test this, I can call

php artisan schedule:run

And this works. The e-mails are sent. But now when I want to start some migrations and seeders, the scheduled tasks also run:

php artisan migrate:refresh --seed

Why is that? If I mess something up and have to call this for some reason, I don't want all my members to receive an e-mail every time.



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

How to set autofocus on Laravel input field using Form::text whilst still setting the class

I can't seem to set autofocus on a input field in Laravel 5.4, whilst also setting the class of the element.

What I've tried:









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

How to make sidebar work with custom javascript

I have a sidebar menu that I'm trying to integrate with a Laravel PHP app. The sidebar appears fine on the display page when I run the app, but the animation, dropdown, and toggle do not work when the application is run.

The HTML has no problems:

<div id="wrapper">
<div class="overlay"></div>

<!-- Sidebar -->
<nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
    <ul class="nav sidebar-nav">
        <li class="sidebar-brand">
            <a href="#">
                Brand
            </a>
        </li>
        <li>
            <a href="#">Home</a>
        </li>
        <li>
            <a href="#">About</a>
        </li>
        <li>
            <a href="#">Events</a>
        </li>
        <li>
            <a href="#">Team</a>
        </li>
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Works <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li class="dropdown-header">Dropdown heading</li>
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li><a href="#">Separated link</a></li>
                <li><a href="#">One more separated link</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Services</a>
        </li>
        <li>
            <a href="#">Contact</a>
        </li>
        <li>
            <a href="https://twitter.com/maridlcrmn">Follow me</a>
        </li>
    </ul>
</nav>
<!-- /#sidebar-wrapper -->

<!-- Page Content -->
<div id="page-content-wrapper">
    <button type="button" class="hamburger is-closed" data-toggle="offcanvas">
        <span class="hamb-top"></span>
        <span class="hamb-middle"></span>
        <span class="hamb-bottom"></span>
    </button>
</div>
<!-- /#page-content-wrapper -->

The CSS is also working with the sidebar

    body {
position: relative;
overflow-x: hidden;
 }
body,
html { height: 100%;}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {background-color: transparent;}

/*-------------------------------*/
/*           Wrappers            */
/*-------------------------------*/

#wrapper {
padding-left: 0;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}

#wrapper.toggled {
padding-left: 220px;
}

#sidebar-wrapper {
z-index: 1000;
left: 220px;
width: 0;
height: 100%;
margin-left: -220px;
overflow-y: auto;
overflow-x: hidden;
background: #1a1a1a;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}

#sidebar-wrapper::-webkit-scrollbar {
display: none;
}

#wrapper.toggled #sidebar-wrapper {
width: 220px;
}

#page-content-wrapper {
width: 100%;
padding-top: 70px;
}

#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-right: -220px;
}

/*-------------------------------*/
/*     Sidebar nav styles        */
/*-------------------------------*/

.sidebar-nav {
position: absolute;
top: 0;
width: 220px;
margin: 0;
padding: 0;
list-style: none;
}

.sidebar-nav li {
position: relative;
line-height: 20px;
display: inline-block;
width: 100%;
}

.sidebar-nav li:before {
content: '';
position: absolute;
top: 0;
left: 0;
z-index: -1;
height: 100%;
width: 3px;
background-color: #1c1c1c;
-webkit-transition: width .2s ease-in;
-moz-transition:  width .2s ease-in;
-ms-transition:  width .2s ease-in;
transition: width .2s ease-in;

}
.sidebar-nav li:first-child a {
color: #fff;
background-color: #1a1a1a;
}
.sidebar-nav li:nth-child(2):before {
background-color: #ec1b5a;
}
.sidebar-nav li:nth-child(3):before {
background-color: #79aefe;
}
.sidebar-nav li:nth-child(4):before {
background-color: #314190;
}
.sidebar-nav li:nth-child(5):before {
background-color: #279636;
}
.sidebar-nav li:nth-child(6):before {
background-color: #7d5d81;
}
.sidebar-nav li:nth-child(7):before {
background-color: #ead24c;
}
.sidebar-nav li:nth-child(8):before {
background-color: #2d2366;
}
.sidebar-nav li:nth-child(9):before {
background-color: #35acdf;
}
.sidebar-nav li:hover:before,
.sidebar-nav li.open:hover:before {
width: 100%;
-webkit-transition: width .2s ease-in;
-moz-transition:  width .2s ease-in;
-ms-transition:  width .2s ease-in;
transition: width .2s ease-in;

}

.sidebar-nav li a {
display: block;
color: #ddd;
text-decoration: none;
padding: 10px 15px 10px 30px;
}

.sidebar-nav li a:hover,
.sidebar-nav li a:active,
.sidebar-nav li a:focus,
.sidebar-nav li.open a:hover,
.sidebar-nav li.open a:active,
.sidebar-nav li.open a:focus{
color: #fff;
text-decoration: none;
background-color: transparent;
}

.sidebar-nav > .sidebar-brand {
height: 65px;
font-size: 20px;
line-height: 44px;
}
.sidebar-nav .dropdown-menu {
position: relative;
width: 100%;
padding: 0;
margin: 0;
border-radius: 0;
border: none;
background-color: #222;
box-shadow: none;
}

/*-------------------------------*/
/*       Hamburger-Cross         */
/*-------------------------------*/

.hamburger {
position: fixed;
top: 20px;
z-index: 999;
display: block;
width: 32px;
height: 32px;
margin-left: 15px;
background: transparent;
border: none;
}
.hamburger:hover,
.hamburger:focus,
.hamburger:active {
outline: none;
}
.hamburger.is-closed:before {
content: '';
display: block;
width: 100px;
font-size: 14px;
color: #fff;
line-height: 32px;
text-align: center;
opacity: 0;
-webkit-transform: translate3d(0,0,0);
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-closed:hover:before {
opacity: 1;
display: block;
-webkit-transform: translate3d(-100px,0,0);
-webkit-transition: all .35s ease-in-out;
}

.hamburger.is-closed .hamb-top,
.hamburger.is-closed .hamb-middle,
.hamburger.is-closed .hamb-bottom,
.hamburger.is-open .hamb-top,
.hamburger.is-open .hamb-middle,
.hamburger.is-open .hamb-bottom {
position: absolute;
left: 0;
height: 4px;
width: 100%;
}
.hamburger.is-closed .hamb-top,
.hamburger.is-closed .hamb-middle,
.hamburger.is-closed .hamb-bottom {
background-color: #1a1a1a;
}
.hamburger.is-closed .hamb-top {
top: 5px;
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-closed .hamb-middle {
top: 50%;
margin-top: -2px;
}
.hamburger.is-closed .hamb-bottom {
bottom: 5px;
-webkit-transition: all .35s ease-in-out;
}

.hamburger.is-closed:hover .hamb-top {
top: 0;
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-closed:hover .hamb-bottom {
bottom: 0;
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-open .hamb-top,
.hamburger.is-open .hamb-middle,
.hamburger.is-open .hamb-bottom {
background-color: #1a1a1a;
}
.hamburger.is-open .hamb-top,
.hamburger.is-open .hamb-bottom {
top: 50%;
margin-top: -2px;
}
.hamburger.is-open .hamb-top {
-webkit-transform: rotate(45deg);
-webkit-transition: -webkit-transform .2s cubic-bezier(.73,1,.28,.08);
}
.hamburger.is-open .hamb-middle { display: none; }
.hamburger.is-open .hamb-bottom {
-webkit-transform: rotate(-45deg);
-webkit-transition: -webkit-transform .2s cubic-bezier(.73,1,.28,.08);
}
.hamburger.is-open:before {
content: '';
display: block;
width: 100px;
font-size: 14px;
color: #fff;
line-height: 32px;
text-align: center;
opacity: 0;
-webkit-transform: translate3d(0,0,0);
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-open:hover:before {
opacity: 1;
display: block;
-webkit-transform: translate3d(-100px,0,0);
-webkit-transition: all .35s ease-in-out;
}

/*-------------------------------*/
/*            Overlay            */
/*-------------------------------*/

.overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(250,250,250,.8);
z-index: 1;
}

Javascript is the part of the program that is not working.

$(document).ready(function () {
var trigger = $('.hamburger'),
    overlay = $('.overlay'),
    isClosed = false;

trigger.click(function () {
    hamburger_cross();
});

function hamburger_cross() {

    if (isClosed == true) {
        overlay.hide();
        trigger.removeClass('is-open');
        trigger.addClass('is-closed');
        isClosed = false;
    } else {
        overlay.show();
        trigger.removeClass('is-closed');
        trigger.addClass('is-open');
        isClosed = true;
    }
}

$('[data-toggle="offcanvas"]').click(function () {
    $('#wrapper').toggleClass('toggled');
});
});

This is the code that I have for the master.blade.php file in my Laravel app

<!DOCTYPE HTML>
<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="http://ift.tt/2apRjw3" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="">
    <link rel="stylesheet" href="">
</head>
<body>
    <div class="container">
        <header class="row">
            @include('layouts.partials.sidebar')
        </header>
        <div id="main" class="row">
            @yield('content')
        </div>
    </div>

    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="http://ift.tt/2aHTozy" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src=""></script>
    <script src=""></script>
</body>
</html>

How do I organize the javascript files in master.blade.php file to make the sidebar work?



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

Join the same MySQL table using eloquent in laravel

I have a DB table with all of my categories, subcategories and parent_category_id column.

What I am trying to do is to join the same table while creating the subcategory navigation to include category slug in URL like so:

/category_slug/subcategory_slug

here is my composer:

public function compose(View $view)
{
    $view->with('categories', \App\Category::join('categories', 'categories.category_id', '=', 'categories.parent_category_id')
        ->where('category_display_type', '=', 'sidebar')
        ->where('category_visibility', '=', 1)->get());
}

the error that I get is:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'categories' (SQL: select * from `categories` inner join `categories` on `categories`.`category_id` = `categories`.`parent_category_id` where `category_display_type` = sidebar and `category_visibility` = 1)  

Please help

I cannot answer my question just yet, but what I have done so far is the following that is now accessing the category_slug, but ignoring the subcategory_slug

public function compose(View $view)
{
    $params = \DB::table('categories as subs')->join('categories as cats', function($join){
            $join->on('cats.category_id', '=', 'subs.parent_category_id')
            ->where('subs.category_display_type', '=', 'sidebar')
            ->where('subs.category_visibility', '=', 1);
})->get();

    $view->with('categories', $params);

}

Do I have to do a double foreach in my view.blade.php file and if yes then how?



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

How to access my model in laravel?

I can't seem to figure out what's wrong with this code. I'm running laravel 5.4.

The error: http://ift.tt/2m4rk2X

The Controller function:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Thread;


class ThreadController extends Controller
{

    public function show($id) {

        return Thread::where('id', '=', $id)->messages();
    }
}

The Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    public function messages()  
    {
        return $this->hasMany(Message::class)->get();
    }


}



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

Stylesheet is not loading in laravel 5

I have two routes

'/test'

which return the memberProfile blade. It works fine. But the other one

'/memberProfile/{id}'

which sends the request to memberController from where it returns the memberProfile blade. But this time the blade could not load the master layouts stylesheets. Instead of searching the stylesheets in path

http://ift.tt/2mBJXcc

it search the css in a path like

http://ift.tt/2m4o3AI

. here is web.php

Route::get('/test', function () {
    return view('members.memberProfile');
});
Route::get('/memberProfile/{id}','memberController@memberProfile'); 

and memberController class

public function memberProfile(Request $request){
        $id = decrypt($request->id);
        $Member = Member::find($id);
        $Member->Research->all();
        $MemberProject = Member::find($id);
        $MemberProject->Project->all();
        $MemberPublication = Member::find($id);
        $MemberPublication->Publication->all();
        return view('members.memberProfile',['members' => $Member , 'memberProject' => $MemberProject , 'memberPublication' => $MemberPublication]);
    }

What is the problem



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

Return search results matching multiple query tags?

I'm using OctoberCMS based on Laravel.

I have an html search field which query string is parsed with php.

Laravel returns database results based on the url tag parameter using MySQL WHERE LIKE.

It works with 1 tag, but how to return results matching multiple tags separated by commas or spaces?

HTML5 Search Input

<form action="/search">
  <input type="search" name="tags" multiple>
  <button type="submit">search</button>
</form>

Single tag search

localhost/search?tags=galaxy

Multiple tag search

commas localhost/search?tags=galaxy%2C+stars%2C+universe
spaces localhost/search?tags=galaxy+stars+universe

This should return any tags matching in the database table's tags column.

The problem is that it sees the query as galaxy AND stars AND universe and not individual tags: galaxy, stars, universe.

Search Results

$query_string = $tags = '';

$query_string = getenv('QUERY_STRING');

// Return search results matching query string
return $query->where('tags', 'like', "%$tags%");

$query is part of OctoberCMS.

Example

results

Problem

problem



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

MySQL Summary Query in Laravel 5.2

I'm working on a project written in Laravel 5.2 that has two tables that need to be queried to produce a summary for the amount of records created by year. Here is a simplified layout of the schema with some sample data:

Matters Table

id  created_at
-----------------
1   2016-01-05 10:00:00
2   2016-03-09 11:00:00
3   2017-01-03 10:00:00
4   2015-05-06 11:00:00

Notes Table

id  created_at
-----------------
1   2015-07-08 10:00:00
2   2016-03-16 11:00:00
3   2017-09-03 10:00:00
4   2017-11-06 11:00:00

Each table has several hundred thousand records, so I'd like to be able to (efficiently) query my data to produce the following results with the counts of each table by year:

year    matters     notes
----------------------------
2015    1           1
2016    2           1
2017    1           2

I need each column to be sortable. Currently, the fastest way I can think of to do this is to have two queries like the following and then combine the results of the two via PHP:

SELECT YEAR(matters.created_at) AS 'year', COUNT(1) AS 'matters'
FROM matters
GROUP BY YEAR(matters.created_at)


SELECT YEAR(notes.created_at) AS 'year', COUNT(1) AS 'notes'
FROM notes
GROUP BY YEAR(notes.created_at)

But I'm wondering if there is a better way, especially since I have to work in sorting each column based on the user's needs.

Any thoughts?



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

Add one to many in form - Backpack laravel

I'm using Backpack for Laravel to provide the backend area of my laravel website.

I'm having the following tables in my database structure:

enter image description here

This is to add sets to a match, and add matches to a tournament.

These are my Models:

Tournament Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class Tournament extends Model
{
    use CrudTrait;

     /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $fillable = ['from', 'to', 'type', 'location', 'place'];

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */

    public function matches()
    {
        return $this->hasMany('App\Models\Match');
    }
}

Match Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class Match extends Model
{
    use CrudTrait;

     /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $table = 'matches';

    protected $fillable = ['opponent'];

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */

    public function sets()
    {
        return $this->hasMany('App\Models\Set');
    }
}

Set Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class Set extends Model
{
    use CrudTrait;

     /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $fillable = ['self', 'opponent', 'index'];

    public function match()
    {
        return $this->belongsTo('App\Models\Match');
    }
}

Now I would like to have the following when I create a Tournament in backend:

enter image description here

I can already set from, to, type, location and place. But now I would like the possibility to add a match and add sets to that match. This all on one page.

But I'm a bit stuck on how to do this. Can someone help me on my way?



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

Laravel 5.3 doing join on pivot table with same models

I posted a previous question seeing if what I'm trying to do could be done with eloquent relationships and it looks like it isn't possible ( Laravel 5.3 Many to many relationship with same model ) .

So now I'm trying to write the query with query builder and have this:

return $relationships = DB::table('landlord_contact_landlord_contact')
            ->where('landlord_contact1_id', $id)
            ->orWhere('landlord_contact2_id', $id)
            ->join('landlord_contacts', function($join){
                $join->on('landlord_contacts.id', '=' , 'landlord_contact_landlord_contact.landlord_contact1_id');
            })
            ->get(['landlord_contact_landlord_contact.id AS relationshipID','landlord_contact_landlord_contact.type' , 'landlord_contacts.*']);

Lets say I have a contact named Jim with an id of 1

And another contact named Tom with an id of 2

What I'm trying to do is have each contact have relationships with other contacts. The table "landlord_contact_landlord_contact" is the pivot table and has "landlord_contact1_id" and "landlord_contact2_id" to join the 2 contacts. Now if I create a record, connecting Jim to Jon and have landlord_contact1_id = 1 and landlord_contact2_id = 2 that's great. But how can I make the query work on both columns so I don't have to create 2 records for each relationship.

I want to search on both columns for the current landlord's id and then do a join either on landlord_contact1_id or landlord_contact2_id depending on which one isn't the current landlords ID.

Note : In my previous post, I used the table name User, but have since renamed everything to Landlord Contacts



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

Querying Laravel Eloquent Relationship

I have three tables.

  • Categories
  • Products
  • Brands

I have a relation on my categories table to the products like so:

public function products()
{
    return $this->belongsToMany('App\Product','product_sub_categories','subcategory_id','product_id');
}

I have a relation on my Products table to the brands like so:

public function manuf()
    {
        return $this->belongsTo('App\Brand','brand');
    }

I'm querying the categories table to return products of that category by a certain brand.

For example.

I wan to see all products in Cars category with the brand Fiat.

I've tried the following but I feel Im missing something..

 $search = 'fiat';
 $products = $category->products()->where(function($query) use ($search){
                    $query->brand->name = $search;
                })->get();



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

laravel 5 redirect route to external url

I am in the process of moving a website to a new version of the site that has been created to Laravel 5, however I need to link to some old static content in a subdirectory on my old site, so I would like to create a route that automatically re-directs any querys to a specific sub-directory to to the old site.

For example:

user goes to: http://ift.tt/2lva17K

I want it to redirect to:

http://ift.tt/2l8nAOz

and I want to have it do this for anything that comes in as

http://ift.tt/2lvadUQ ... I want it to duplicate the same path but redirected to the old site. I don't want to have to put in each brochure, as every once in a while a new brochure gets added...



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

Dynamic routing in laravel 5.2

I want to generate a url like 'top-hotels-in-india' here hotels and india is dynamic values that user will search. When i am using

Route::get("top-hotels-in-india",'Controller@method');

it works, but this is a static url i want this dynamic so changed this into

Route::get("top-{things}-in-{country}",'Controller@method');

But its not working. If i replace - with / its works perfect but i want hyphen in url instead of slash. What should i do to generate this types of routes. Please help.



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

Laravel 5.4 Add a difference between views

I use the same view to show one post and random post

routes

Route::get('posts/{id}', 'PostsController@show')->name('posts.show');
Route::get('get-random-post', 'PostsController@getRandomPost');

methods in PostsController

public function show($id) {
        $post = Post::findOrFail($id);
        return view('posts.show', compact('post'));
    }


public function getRandomPost() {
        $post = Post::inRandomOrder()
            ->where('is_published', 1)->first();
        return redirect()->route('posts.show', ["id" => $post->id]);
}

but now I need to add a small difference between two views. How can I do that?



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

Daterangepicker in vue not working

I'm loading the daterangepicker and moment globally but its not working, everything is installed. Have a looks at my code:

window._ = require('lodash');

window.$ = window.jQuery = require('jquery');

window.moment = require('moment');
require('daterangepicker');

require('bootstrap-sass');

import Vue from 'vue';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';


import axios from 'axios';
import noty from 'noty';
import sweetalert from 'sweetalert';

window.Vue = Vue;
Vue.use(VueRouter);

window.axios = axios;
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};

Table

import {ServerTable, Event} from 'vue-tables-2';
Vue.use(ServerTable, {
filterByColumn: true,
compileTemplates: true,
responseAdapter: function (resp) {
    return {
        data: resp.data,
        count: resp.total
    }
},
templates: {
    open: 'open-vuetable-resource'
},

sortIcon: {
    base:'fa',
    up:'fa-sort-amount-asc',
    down:'fa-sort-amount-desc'
},
rowClassCallback: function(row) {return `row-${row.id}`},

datepickerOptions: {
    showDropdowns: true
}
});

Vue.component('open-vuetable-resource', {
props: ['data'],
template: `<a :href="data.ShowAdmin" class='btn btn-primary'><i class="fa        fa-eye"></i></a>`
});

Create table

$(document).ready(function() {
new Vue({
    el: "#people",
    data: {
        columns: ['id', 'username', 'email', 'created_at', 'open'],

        options: {
            filterable: ['id', 'username', 'created_at', 'email'],
            sortable: ['id', 'username', 'created_at', 'email'],
            dateColumns: ['created_at']
        }
    }
});
});

I have tried with moment(created_at), but still nothing. Any tips on why the datepicker is not working for me?

I'm running out of ideas :D

Thanks!



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

How to send data from one table to another in Laravel?

I have problem with send data from one table to another. I want delete data from first table too. Is it possible to do that operation under one button ? I have my records in table. I don't know how to route this operation.

This is my idea,but it didnt work. I get error Invalid route action

    public function dodaj($id)
{   
    $operacje = DB::table('operacja')->where('id',$id)->get();
    $operacje = DB::table('potwierdzona')->insert($operacje);
    $operacje = Operacja::findorFail($id);
    $operacje->delete();
    return redirect('patients');
}

My route is Route::post('potwierdzone/$id/dodaj/','PotwierdzonaController');



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

Laravel artisan migrate:refresh xammp give's weird error

I used to work on a mac with laravel 5.3 / 5.4 no prob's with laravel whatsoever.

But since i'm back on my windows machine the problems start to come, i started with installing xammp, composer and then downloaded laravel. setted my DB settings in de .env file up and then I wanted to test the db connection with php artisan migrate:refresh which gave a error. see image

I did not change anything to the migration's so there shouldn't be any problem with it and since i'm kinda stuck HELP!



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

unable to create directory in laravel 5.1 when upload image?

Error : Unable to create the "http:/localhost/shopping/public/src/img/" directory

my code :
$imageName = $product->id . '.' . 
        $request->file('image')->getClientOriginalExtension();
                $request->file('image')->move(
        url().'/public/src/img/', $imageName
        );



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

Laravel 5 - Allow to pass only FormRequest rules fields

I would like to use FormRequest validation in which allow request fields only in rules() return array keys.

In the below code, I would like to allow request fields only 'os', 'number', 'version'. If request include the other field , return error response.

How can I modify the code ?

public function rules()
  {
    return [
        'os' => [
            'required',
            \Rule::in(['android', 'ios']),
        ],
        'number' => 'required|integer',
        'version' => ['required', 'http://regex:/^\d+.\d+.\d+$/'],
    ];
  }



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

auth::attemp not working properly laravel

My login in laravel isnt working properly. I've been stuck here for a long time now. This is my login controller code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class UsersController extends Controller
{
protected function dashboard(Request $request)
{

    if (Auth::attempt(array('account_number'=>$request['accountnumber-login'], 'password'=> $request['txt-password']))) {
        return redirect()->intended('viewdashboard');
    }

} 

protected function viewdashboard()
{
    return view('dashboard');
}
}

..in this controller the 'account-number' is the account number column in the database and the 'password' is the password column in the database. I've done everything correctly yet it does not redirect me to the dashboard view. Please help

and this is my html form

<html>
<form action="dashboard" method="GET">
<input type="number" name="accountnumber">
<input type="password" name="password">
</form

</html>

this is my web route folder

Route::get('dashboard', function(){
return view('dashboard_view');
}

pls help, please.



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

Laravel search mutiple fields

i currently have a search function on my website, i need it to search 3 fields - appid, mobilenumber, email .

Right now once the user enters the data in the search box it searches all 3 but its not working.

Data is collected using GET.

Here is my query

http://ift.tt/2mzXaST

    $mobile = INPUT::get('searchall');
    $email = INPUT::get('searchall');
    $appid = INPUT::get('searchall');

$data = DB::table('leads')
->when($mobile, function($query) use ($mobile){
                return $query->where('MobilePhone', $mobile);
            })

            ->when($email, function($query) use ($email){
                return $query->where('Email', $email);
            })

            ->when($appid, function($query) use ($appid){
                return $query->where('AppID', $appid);
            })

->get();

So i need it to search each field until it finds the correct field value.



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

Laravel Newbie ? about DB controller

I'm learning Laravel and I tried to create a page where Laravel populates a table from DB, but I have an error (I did everythin what was in this PDF file (Page 67-69))

Error message:

FatalThrowableError in ListProductsController.php line 16: Parse error: syntax error, unexpected end of file, expecting function (T_FUNCTION)

ListProductsController.php

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ListProductsController extends Controller
{
    public function inventory(){
    $inventory = DB::select('select * from inventory');
    return view('inventory',['inventory'=>$inventory]);
}

My route:

Route::get('inventory','ListProductsController@inventory');

What goes wrong?



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

Storing and accessing multiple images in laravel

I am trying to make a site where i can list the name of products and when those name are clicked it will take to its detail page. On detail page it will show its description along with the images(more than 2) uploaded during posting. I did up to storing images by using relationship. For this i have made two tables named, "Product" and "ProductsPhoto" and established relationship in their model. It uploads image but it stores image in storage base folder of laravel. Controller for this is:

    public function uploadSubmit(UploadRequest $request)
{
    // Coming soon...
     $product = Product::create($request->all());
    foreach ($request->photos as $photo) {
        $filename = $photo->store('photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
    }
    return redirect('/upload/{id}');;
}

My route for it is:

    Route::get('/upload', 'UploadController@uploadForm');
    Route::post('/upload', 'UploadController@uploadSubmit');
    Route::get('/upload/{id}','UploadController@show');

And I am being unable to show the images in detail page.Actually I did all these by following a tutorial. I don't know it nicely. So can you teach me to upload multiple images for one particular post and show them in their detail page either by establishing eloquent relationship or any by favorable methods. I just need is to upload many images for one post and show those all images for that post in detail page.



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

laravel 5.4 embed image in mail

I have just upgraded my 5.2 install of laravel to 5.3 and then to 5.4 following the official upgrading methods.

I am now trying to use one of the new features, to create a markdown formated email.

According to the documentation found at: http://ift.tt/2lQHtGR

To embed an inline image, use the embed method on the $message variable within your email template. Laravel automatically makes the $message variable available to all of your email templates, so you don't need to worry about passing it in manually:

However, this:

<img src="">

will produce the following error:

Undefined variable: message

Am I missing something? Or is there something undocumented in the upgrading guides?



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

laravel relation hasMany accessor count()

I've got these models

Machine:

->id
->...

Server

->id
->machine_id
->is_suspended

Relations from Machine model:

public function servers()
{
    return $this->hasMany('App\Server');
}

//with suspended servers
public function getFreePortsAmountAllAttribute()
{
    return $this->servers->count();
}

//without suspended servers
public function getFreePortsAmountAttribute()
{
    return $this->servers->where('servers.is_suspended', false)->count();
}

Using this relations, when I create 2 servers (1 suspended, 1 not suspended) and calling:

dd(Machine::find(1)->free_ports_amount);

Returns 0, so for some reason the accessor doesn't work. Any idea why?



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

lundi 27 février 2017

How to filtering chart between start date and end date laravel

i made a report charts using ConsoleTVs/charts packages...

i try making report charts by between start date and end date... but variable not defined. variable obtained from Json response from the controller.

Im using ajax to throwing date to controller.

this my code:

LaporanController.php

public function cari(Request $request, $tgl_awal, $tgl_akhir)
    {
      $data_top_user = DB::table('radacct')
                    ->select(array('username', DB::raw('Round((sum(acctoutputoctets))/1048576,0) as jumlah')))
                    ->whereBetween('acctstarttime', [$tgl_awal, $tgl_akhir])
                    ->orderBy('jumlah','desc')
                    ->limit(10)
                    ->get();

              $chart_laporan = Charts::create('bar', 'highcharts')
                    ->template('teal-material')
                    ->title('10 pengguna pemakai bandwith terbanyak')
                    ->elementLabel('Jumlah')
                    ->responsive(true)
                    ->labels($data_top_user->pluck('username'))
                    ->values($data_top_user->pluck('jumlah'));

                    return response()->json([
    ['chart_laporan' => $chart_laporan]
]);

                    /*return view('laporan.laporan_nas')
                            ->with(['chart_laporan' => $chart_laporan]);*/
    }

and my Route web.php

    Route::post('/laporan_device/cari/{tgl_awal}/{tgl_akhir}','Graph\LaporanController@cari');

and my view
<div class="box-body">
            <div class="table-responsive">
              <form class="form-inline" id="cari">
                <div class="form-group">
                  <label for="exampleInputName2">Tanggal awal</label>
                  <input type="text" class="form-control" id="tgl_awal" >
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail2">Tanggal Akhir</label>
                  <input type="text" class="form-control" id="tgl_akhir">
                </div>
                <button type="submit" class="btn btn-default">Cari</button>
              </form>
            </div>
          </div>

    $("#cari").submit(function(event){

        // Prevent default posting of form - put here to work in case of errors
        event.preventDefault();

        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.


        // Fire off the request to /form.php

          $.ajax({
              type: 'post',
              url: window.location +'/cari/'+$("#tgl_awal").val()+'/'+$("#tgl_akhir").val(),
              data: {
                '_token': $('input[name=_token]').val(),
                'tgl_awal': $("#tgl_awal").val(),
                'tgl_akhir' : $("#tgl_akhir").val(),
              },
            success: function(data) {
              if ((data.errors)) {

              }
              else{
                $('.chart_view').removeClass('hidden');
                $('.box_charts').append('<div class="box-header"><h3 class="box-title">Daftar</h3></div><div class="box-render">  {!! $chart_laporan->render() !!}</div>');
                $.notify({
                  message: 'Data Berhasil Diubah',
                },{
                  element: 'body',
                    position: null,
                    type: "success",
                    offset: 20,
                    spacing: 10,
                    z_index: 1031,
                    delay: 1000,
                    timer: 1000
                });
                    oTable.ajax.reload();
              }

          },
        });
          e.preventDefault()

    });
  </script>

can someone help me? please help me thank you before...



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

Laravel Sub-domain Routing Setup

I currently have a Laravel site up and running on Godaddy hosting.

What I want is to have a sub-domain.

mysite.xyz - main site

backoffice.mysite.xyz - admin

The main site is currently working.enter image description here

But the backoffice is notenter image description here

Here is my current routes fileenter image description here

How do I make this work?



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

found error in laravel 5.4,Property [categories] does not exist on this collection instance

I am trying to display the product listing on listing page of the product. Each product has category.My table structure

categories
id  name  description
1   Cat1  Category 1
2   Cat2  Category 2

This is the category table having id name and description

products
    id  name  description category_id
    1   pro1  product 1        1
    2   pro2  product 2        2

This is the product table having category_id.

Product Model
    public function categories() {        
            return $this->belongsTo("App\Category");
        }

This is the product model where the products are belongs to category

Category Model
         public function products() {
        return $this->hasMany("App\Product");
    }

This is the Category model where the Category has many product

Now in the product controller on listing function I want the list of product with category name

public function index()
    {
        $product = Product::with('categories')->get();
        print_r($product->categories);die;
        return view('product.index')->with("list",$product);
    }

I want my Output should be

products
        id  name  description category name
        1   pro1  product 1        cat1
        2   pro2  product 2        cat2

I found this error "Property [categories] does not exist on this collection instance."



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

Use unique validation for only specific record in database table in Laravel 5

I'm trying to validate unique question for specific book_id it means is should be unique only specific record.

table: questions

$title = this is question 1

$book_id = 12

TRUE = if question not posted for $book_id = 16, user can post same question.

Display Error = if question posted for $book_id = 12, user not able to post.

This is what I tried so far

"required|unique:questions,question,book_id".$book_id, "required|unique:questions,question,book_id,!".$book_id, "required|unique:questions,question,NULL,id,book_id,".!$book_id,



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

cach and session problems in laravel 5.3

when run my laravel application it is work great but after 10k user register in my website in one day and 100 k visitor suddenly authentication system failed and every refresh in my website take you to another authentication member

I solved this problem by removing all files in /storage/framework/cahch and sessions folder

what is the reason of this problem and how to solve it ps: using laravel authentication system



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

calling data from database from controller to view using laravel

Controller:

public function index() {
        $data = DB::table('tusers','tbills','tpackages')
            ->join('tbills', 'tusers.user_id', '=', 'tbills.user_id')
            ->join('tpackages', 'tbills.package_id', '=', 'tpackages.package_id')
            ->select('tusers.user_id','tusers.company_name','tusers.first_name', 'tbills.account_no', 'tpackages.package_name','tbills.start_date','tbills.end_date','tbills.bill_status')
            ->get();

        return View::make('account')->with('data',$data);
    }

`

view:

@forelse($data as $value)
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td>

I want to call $data from packagecontroller to account.blade but there is an error

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "tusers" does not exist
LINE 1: ... "tbills"."end_date", "tbills"."bill_status" from "tusers" i...
^ (SQL: select "tusers"."user_id", "tusers"."company_name", "tusers"."first_name", "tbills"."account_no", "tpackages"."package_name", "tbills"."start_date", "tbills"."end_date", "tbills"."bill_status" from "tusers" inner join "tbills" on "tusers"."user_id" = "tbills"."user_id" inner join "tpackages" on "tbills"."package_id" = "tpackages"."package_id")

Thanks for your help.



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

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

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

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

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

My ajax:

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

arrayofproductsandthereassociates is populated, looks like this:

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

When Laravel gets this payload using this controller code:

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

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

The array looks all messed up at the print_r()

Output:

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

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

Thank you!



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

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

In my Ubuntu VM, I kept getting

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

I have configured my database like this in my .env file

DB_HOST=45.55.88.57
DB_DATABASE=bheng-prod
DB_USERNAME=forge
DB_PASSWORD=*********
UNIX_SOCKET=/var/run/mysqld/mysqld.sock

What else I should look into to prevent this ?


I have a feeling that I have the wrong password.

How do I test my database password ? DB_PASSWORD=********* ?



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

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

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

(original query)

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

(model class)

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

    }
}

and to use it:

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

Thanks!



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

how to get laravel single locale string in blade template?

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

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

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



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

Appends Laravel collection with another collection

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

Collection merge eating up some rows

Any ideas?



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

sending multiple inputs on ajax

i have a form where i get a collection of records, and after being present is shown like this:

  <input name="position" id="nameText" step-id="3" type="number" value="1" class="form-control stepinput">

<input name="position" id="nameText" step-id="4" type="number" value="2" class="form-control stepinput">

<input name="position" id="nameText" step-id="5" type="number" value="3" class="form-control stepinput">

The value is to later sort the records, and the "step_id" attribute is to send via ajax to update the specific record, but my data is not quite looking good. Wich is the best way to send my data to the controller to later being updated the records

My current code:

$('button.update-positions').on('click', function(event){
            event.preventDefault();
            var form = $(this).closest(".steps-form");

            var map = {};
            $(".stepinput").each(function() {

                map[$(this).attr("step-id")] = $(this).val()

            });

        })



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

Laravel flysystem ftpd adapter

I want to use the ftpd Adapter in Laravel to access a Synology NAS, which seems to need this specific adapter http://ift.tt/2mmX2cu, but I get the error

Driver [Ftpd] is not supported.

The file is there:

vendor/league/flysystem/src/Adapter/Ftpd.php

Do I have to register anything that I can use it?



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

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

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

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

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

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

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

Laravel Passport

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



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

project name getting removed from the link in laravel

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

Object not found!

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

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

Error 404

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



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

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

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

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

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

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

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

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

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

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



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

How can I perform this custom input form validation (if the username\e-mail yet exists in the DB) in Laravel?

I am pretty new in Laravel and I have the following doubt about how to implement a custom form input validator.

I explain my situation:

I have this view that contains a registration form:

@extends('layouts.app')

@section('content')

    <div class="row">

        <div class="col-md-12">

            <!--<h1 class="page-header"><i class="glyphicon glyphicon-file"></i> Aggiungi un utente albergatore</h1>-->
            <h1 class="page-header"><i class="fa fa-bed" aria-hidden="true" style="margin-right: 2%"></i>Aggiungi un utente albergatore</h1>

            @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> Sono stati riscontrati errori nel tuo input.<br /><br />
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li></li>
                        @endforeach
                    </ul>
                </div>
            @endif


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

                <div class="form-group">
                    <label>Nome</label>
                    <div class="input-group">
                        <div class="input-group-addon"><i class="fa fa-user"></i></div>
                        <input type="text" name="name" class="form-control" placeholder="Inserisci il tuo nome">
                    </div>
                </div>

                <div class="form-group">
                    <label>Cognome</label>
                    <div class="input-group">
                        <div class="input-group-addon"><i class="fa fa-user"></i></div>
                        <input type="text" name="surname" class="form-control" placeholder="Inserisci il tuo cognome">
                    </div>
                </div>

                <div class="form-group">
                    <label>Username</label>
                    <div class="input-group">
                        <div class="input-group-addon"><i class="fa fa-user"></i></div>
                        <input type="text" name="login" class="form-control" placeholder="Inserisci il tuo username">
                    </div>
                </div>

                <div class="form-group">
                    <label>E-mail</label>
                    <div class="input-group">
                        <div class="input-group-addon"><i class="fa fa-envelope"></i></div>
                        <input type="email" name="email" class="form-control" placeholder="Inserisci il tuo indirizzo e-mail">
                    </div>
                </div>

                <div class="form-group">
                    <label>Conferma e-mail</label>
                    <div class="input-group">
                        <div class="input-group-addon"><i class="fa fa-envelope"></i></div>
                        <input type="email" name="email_confirmation" class="form-control" placeholder="Inserisci il tuo indirizzo e-mail">
                    </div>
                </div>

                <div class="form-group">
                    <label>Password</label>
                    <div class="input-group">
                        <div class="input-group-addon"><i class="fa fa-lock"></i></div>
                        <input type="password" name="pass" class="form-control" placeholder="Inserisci la tua password">
                    </div>
                </div>

                <div class="form-group">
                    <label>Conferma password</label>
                    <div class="input-group">
                        <div class="input-group-addon"><i class="fa fa-lock"></i></div>
                        <input type="password" name="pass_confirmation" class="form-control" placeholder="Inserisci la tua password">
                    </div>
                </div>


                <div class="form-group">
                    <label>Captcha</label>
                    <div class="input-group">
                        {!! app('captcha')->display(); !!}
                    </div>
                </div>

                

                <button type="submit" class="btn btn-default">Submit</button>

            </form>

        </div>

    </div>


@endsection

As you can see in the previous code this view contains this section that iterates on the possible "syntax" errors and show it in this page if the input is not validated:

        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <strong>Whoops!</strong> Sono stati riscontrati errori nel tuo input.<br /><br />
                <ul>
                    @foreach ($errors->all() as $error)
                        <li></li>
                    @endforeach
                </ul>
            </div>
        @endif

This is the controller method that handle the form submission:

public function store(Request $request) {

    Log::info('store() START');

    $data = Input::all();

    Log::info('INSERTED DATA: '.implode("|", $data));

    // Regole di validazione sintattica del contenuto del form di registrazione:
    $rules = array(
        'name' => 'required',
        'surname' => 'required',
        'login' => 'required',
        'email' => 'required|email|confirmed',
        //'email_confirmation' => 'required|email|confirmed',
        'pass' => 'required|required|min:6',
        //'passConfirm' => 'required',
        'g-recaptcha-response' => 'required|captcha',

    );

    // Validazione sintattica del form di registrazione:
    $validator = Validator::make($data, $rules);

    /*
     * Se il form di registrazione contiene dati sintatticamente errati, ritorna alla pagina di registrazione
     * passando la lista dei messaggi di errore da visualizzare
     */
    if ($validator->fails()){
        return Redirect::to('/registration')->withInput()->withErrors($validator);
    }

    // Altrimenti se i dati inseriti sono sintatticamente corretti:
    else {

        // Controlla se esiste un utente con la stessa e-mail:
        $resultCheckEmail = DB::select('select * from pm_user where email = ?', [$data['email']]);
        Log::info('blablabla');

        if (empty($resultCheckEmail)) {

        }

        // Controlla se esiste un utente con lo stesso username:
        $resultCheckUsername = DB::select('select * from pm_user where email = ?', [$data['login']]);
        Log::info('blablabla');

        if (empty($resultCheckUsername)) {

        }
    }
}

As you can see in this code I define a $rules array that defines the validation rules of the data submitted and I check if these data ara valid by this line:

$validator = Validator::make($data, $rules);

If the validation fails it come back to the registration form view passing the errors by this line:

return Redirect::to('/registration')->withInput()->withErrors($validator);

If the input validation is correct it enters into this block of code:

    else {

        // Check if yet exists an user with the same e-mail in the database:
        $resultCheckEmail = DB::select('select * from pm_user where email = ?', [$data['email']]);
        Log::info('blablabla');

        if (empty($resultCheckEmail)) {
            // RETURN TO THE REGISTRATION FORM WITH A SPECIFIC ERROR MESSAGE
        }

        // Check if yet exists an user with the same username in the database:
        $resultCheckUsername = DB::select('select * from pm_user where email = ?', [$data['login']]);
        Log::info('blablabla');

        if (empty($resultCheckUsername)) {
            // RETURN TO THE REGISTRATION FORM WITH A SPECIFIC ERROR MESSAGE
        }
    }

Here I have also to check if yet exists an user having the same e-mail and\or the same username (because I can't register 2 users having the same e-mail and/or the same username).

So if exists a user having the same e-mail and/or the same username I have to come back to the registration form page with a specific error that have to be shown in the same place of the previous error message, here:

I think that I have to put in some way these messages into the $errors array.

How can I do it? What is the smarter way to handle this situation?



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

Using Multiple where condition and variables in laravel 5 MYSQL Query

This my query in which I want to use variables to be compared with the fields in the database table to get the price field from it.

 $price = DB::table('price')
       ->where([
    ['days_id', '=',  $days] , ['deals_id' , '=', $selected_deal]
        ])
       ->value('price');



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

How to get user(authenticated) information even when user is not logged in?

I want to show user information publicly from built-in users table in Laravel. More specifically, Anyone can see user information(name, email, username) without logged in. I've used these in blade file:




But it only works when user logged in otherwise shows errors. Even I've used ELOQUENT in controller and have passed $user object with by view. I'm attaching images so that you can understand my problem. This is my PagesController file enter image description here

And this is my welcome.blade.php file

enter image description here



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

Laravel: yield('content')

I created a view:

@extends('layouts.dashboard')
@section('wrapper')

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

And: layouts.dashboard

<div class="main-panel">
    @yield('section')
</div>
            <footer class="footer">

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



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

Error in Relationship of tables

Im having a error when i try to get some data between 2 tables using eloquent. The error that is giving me is:

Error:
Trying to get property of non-object (View: 

This is my app information

DB:
survey:
- id;
- template_id;
- title;


templates:
- id;
- name;
- internal_name;

SurveyModel:
 public function theme(){

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


View:

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

        <tr>
        <td></td>

</tr>
@endforeach



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

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

I did a fresh clone of my L5 project on my Mac OS.

Going to my site via Chrome, I kept getting this error

ErrorException in Filesystem.php line 81:
file_put_contents(/Applications/MAMP/htdocs/code/bunlong-web-app/bootstrap/cache/services.json): failed to open stream: No such file or directory

I already did :

chmod -R 777 bootstrap/ storage/ vendor/

and my file permissions look like this :

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

I tried

composer dump-autoload

I got

Generating autoload files

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



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

Laravel 5 get random post

There is a link "Get Random Story" <a href="#" class="btn-get-random-post">Get Random Story</a> on the main page of my site, on click I need to get random post from DB and show it on the same window. I use Laravel 5.4.

class PostsController extends Controller
{

public function index() {
    return redirect('/');
}

public function show($id) {
    $post = Post::findOrFail($id);
    return view('posts.show', compact('post'));
}

public function getRandomPost() {
    $post = Post::inRandomOrder()->first();
    return view('posts.show', compact('post'));
}
}

routes

Route::get('posts', 'PostsController@index');
Route::get('posts/create', 'PostsController@create');
Route::get('posts/{id}', 'PostsController@show');
Route::post('posts', 'PostsController@store');
Route::post('publish', 'PostsController@publish');
Route::post('delete', 'PostsController@delete');
Route::post('get-random-post', 'PostsController@getRandomPost');

js

$(document).ready(function() { 
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('.btn-get-random-post').on('click', function(){

    $.ajax({
        type: 'post',
        url: './get-random-post',               
        error: function(jqXHR, textStatus, errorThrown) { 
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
    return false;
});

});

And I have 2 problems here
1. Method getRandomPost() returns post, but how to display it? I want to get as result page with url mysite/post/{id} like url from method show.
2. Is there any way to get and display random post (with url mysite/post/{id}) without AJAX?



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

cannot using attach() method in laravel

I have the following relations set up:

public function notes()
{
    return $this->belongsToMany(Note::class);
}


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

and pivot table like this:

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

now, i used Attach() method:

$note->tags()->attach($tagsIds);

but that is not work and get this error:

[Symfony\Component\Debug\Exception\FatalErrorException] Cannot instantiate interface phpDocumentor\Reflection\DocBlock\Tag



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

Dynamic Subcategories Navigation with category and subcategory slug laravel

I have a table in MySQl that contains list of all categories and subcategories. Each subcategory includes assigned parent_category_id

The page controller is as follows:

Route::get('/', 'PageController@home');
Route::get('{category}', 'PageController@category_show');
Route::get('{category}/{subcategory}', 'PageController@subcategory_show');

Now to the main part of the question, I am trying to create Top Navigation and Sidebar Navigation for subcategories. The top navigation is pretty simple and this is how I managed to accomplish this in my NavigationComposer.php

class NavigationComposer
{
    public function compose(View $view)
    {
        $view->with('categories', \App\Category::where(
            array(
            'category_display_type' => 'header',
            'category_visibility' => 1
        ))->get());
    }
}

I have tried to do the same with my subcategories in my SidebarnavComposer.php All works just fine except that I need to have the category slug in the URI when I switch to one of the categories. So far I am only able to get parent_category_id in URI. I have tried to create a join, but getting some errors.

Here is the content of my SidebarnavComposer.php

class SidebarnavComposer
{
    public function compose(View $view)
    {
        $view->with('subcategories', \App\Category::where(
            array(
            'category_display_type' => 'sidebar',
            'category_visibility' => 1
        ))->get());

    }

}

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

Thanks in advance



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

How laravel `Auth:user()` or `Auth:id()` works

How laravel Auth:user() or Auth:id() works

Is it resides in session or database.

I searched but not get good article.

Please help to understand. I know I will get many down-votes ;)



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

Update records hierarchy

I need to update herarchies, for example one parent has points 5 then its children's point will increase by +5 and so on till the end.

I am not sure what should I user here should do this in mysql or laravel ? which is the best option and also I could like to know if anyone has any good example like this.

looking for some good Idea on this, Thanks in advance



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

Query if a relationship exists with conditions in Laravel

I have a model Foo that contains a hasMany relationship to Bar.

I have a query similar to the following:

$r = Foo::with(['bar' => function($query) {
    $query->where('someProp', '=', 10);
})->get()

However, I want to only return the Foo object if item has a Bar object that satisfies the query.

I'm aware that you can do something like this:

$r = Foo::has('bar')
    ->with(['bar' => function($query) {
        $query->where('someProp', '=', 10);
    })->get();

But that checks if any bar items exists. Not if a bar item exists with someProp = 10

How can I do this?



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

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

Hello stack community !

I work on Ionic 2.0 with Laravel.php as backend. And I have a simple question :

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



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

Auth Issue when upgrading from Laravel 5.2 to Laravel 5.3

I have following the official guide to upgrade from laravel 5.2 to laravel 5.3: http://ift.tt/29vUJ0Q

Because I needed some customizations to the default authentication I have copied the login function to Http\Controllers\Auth\AuthController.php.

Now, when I updated, the `AuthController.php' was divided into several other files.

I have copied the login function to Http\Controllers\Auth\LoginController.php

Now, I am getting the following error when trying to login:

BadMethodCallException in Controller.php line 82:

Method [getCredentials] does not exist.

The login functions below (Might not matter):

public function login(Request $request)
{
$this->validate($request, [
    'email' => 'required|email', 
    'password' => 'required',
]);

$credentials = $this->getCredentials($request);

// This section is the only change
if (Auth::validate($credentials)) {
    $user = Auth::getLastAttempted();
    if ($user->active) {
        Auth::login($user, $request->has('remember'));

        ActivityLog::add("User has successfully logged in.", $user->id);

        return redirect()->intended($this->redirectPath());
    } else {
        return redirect($this->loginPath) // Change this to redirect elsewhere
            ->withInput($request->only('email', 'remember'))
            ->withErrors([
                'active' => 'This account has been suspended.'
            ]);
    }
}

return redirect($this->loginPath)
    ->withInput($request->only('email', 'remember'))
    ->withErrors([
        'email' => $this->getFailedLoginMessage(),
    ]);

}

How do I fix this?



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

Laravel 5.3 how to write custom casted attribute

I have Trait for custom cast types and added currency cast type but it works only when accessing attribute:

trait ModelCastsTrait {

protected function castAttribute($key, $value)
{
    if (is_null($value)) {
        return $value;
    }

    switch ($this->getCastType($key)) {
        case 'int':
        case 'integer':
            return (int) $value;
        case 'real':
        case 'float':
        case 'double':
            return (float) $value;
        case 'string':
            return (string) $value;
        case 'bool':
        case 'boolean':
            return (bool) $value;
        case 'object':
            return $this->fromJson($value, true);
        case 'array':
        case 'json':
            return $this->fromJson($value);
        case 'collection':
            return new BaseCollection($this->fromJson($value));
        case 'date':
        case 'datetime':
            return $this->asDateTime($value);
        case 'timestamp':
            return $this->asTimeStamp($value);
        case 'currency':
            return new CurrencyCast($value, $this);
        default:
            return $value;
    }
}

}

How make custom attribute casting work in reverse, convert value to castable type?



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