vendredi 31 mars 2017

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 Chebli Mohamed

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 .. http://ift.tt/2okv9m5 it should load my admin application

I got http error 500 when i tried to access http://ift.tt/2okv9m5

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



via Chebli Mohamed

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. move from /tmp to /media
  4. create thumbnail
  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 Chebli Mohamed

CRON JOB Laravel & Digital Ocean

I am trying to implement some CRON Jobs on a LEMP Stack with Ubuntu 14.10. I'm using Laravel 5.4. All this hosting in a Digital Ocean droplet.

CRON Table

* * * * * /usr/bin/php /var/www/laravel/artisan schedule:run >> /dev/null 2>&1

Kernel.php

protected function schedule(Schedule $schedule) {
        $schedule->command('commandA')->everyMinute();
        $schedule->command('commandB')->everyMinute();
}

Guess what, it is not working.

Here is what I tried :

If I run manually the command /usr/bin/php /var/www/laravel/artisan schedule:run it is working and the tasks are triggered once.

The output of which php is /usr/bin/php

Everything seems to be fine but I must have forgot something...



via Chebli Mohamed

Cannot open file "/tests/ExampleTest.php" Laravel5 using Windows10

i am running phpunit testing in laravel5 on windows 10,and getting this error by running the following command.

Cannot open file "/tests/ExampleTest.php",
D:\wamp64\www\forum\vendor\bin>phpunit /tests/ ExampleTest.php

Can you please suggest me what could be the issue?



via Chebli Mohamed

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 Chebli Mohamed

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 Chebli Mohamed

Correct way of implementing form select in Laravel 5.1?

Why is that (+) sign generates an error "Unsupported operand types" Anyone could tell me why?If so,What is the correct way?

    <div class="form-group">

        {!! Form::select('category', 
            (['0' => 'Select Province'] + $location), 
                null, 
                ['class' => 'form-control']) !!}
    </div>



via Chebli Mohamed

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: http://ift.tt/2nTj6eV 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 Chebli Mohamed

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://ift.tt/2opZxZm}}" @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 Chebli Mohamed

Laravel routes and route:cache

I have the following in my routes.php

Route::pattern('slug', '[a-zA-Z0-9\-_\/+]');
$slug = Request::path();
if(isset($slug)) {
    $slug_array = explode('/', $slug);
    if($slug_array[0] != 'version' && $slug_array[0] != 'api') {
        $slug = explode($slug, '/');
        Route::any('/{slug}', 'Frontend\PagesController@index')->where('slug', '[a-zA-Z0-9\-_\/]+');
    } else {
        if($slug_array[0] == 'api') {
            Route::any('/{slug}', 'Custom\ApiController@init')->where('slug', '[a-zA-Z0-9\-_\/]+');
        }
    }
}

When I do a php artisan route:cache the routes for Route::any('/{slug}', 'Frontend\PagesController@index')->where('slug', '[a-zA-Z0-9\-_\/]+'); work fine. But the 'Custom\ApiController@init' is completely ignored.

How can I go about it that it's also cached?



via Chebli Mohamed

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 Chebli Mohamed

Laravel 5.3 JWT Auth Login Once via custom token

In parallel to credentials based authentication Auth::once($credential_array) I need another method to login that should work for only udid attribute of user model.

Auth::once(['udid' => '00123456789XYZ']);

How can I implement it?
Do I need to implement custom guard or user provider here or I can extend existing?

I am using Eloquent User Provider.



via Chebli Mohamed

Laravel 5 next and previous paging

Hello I have a list of max 5 articles in my homepage but I have many more articles and I would like to show these articles in other pages. So when I see more old posts, I would like to do a pagination like user home page / 1 when I get it as a result of posting it as url. But I do not follow the correct paths when I make directions. I need to change the following lines of code to help you change the point, good day, good day app/Http/Controller/HomeController:

public function deneme($page){
        $url = url()->full();
        $myUrl = explode('/', $url);
        $uz= sizeof($myUrl);
        $myUrl = $myUrl[$uz-1];
        if ($myUrl == 'work.com'){
            $yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();

            $posts = array_slice($yazilar->getIterator()->getArrayCopy(),0,5);
            return view('backend.pages.anasayfa')->with('yazilar', $posts);
        }else{
            $baslangic = $page*5;
            $yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();

            $posts = array_slice($yazilar->getIterator()->getArrayCopy(),$baslangic,5);
            return view('backend.pages.anasayfa')->with('yazilar' ,$posts);
        }

    }

Routers/web.php:

Route::get('/{page}', 'HomeController@deneme');

View :

<ul class="pager">
                    <li class="next">
                        <a href="">Older Post &rarr;</a>
                    </li>
                </ul>



via Chebli Mohamed

OAuth Not Working With Laravel

i am trying to connect my magento 2.0 store from my laravel application, when i make OAuth call from laravel to my magento 2.0 store laravel throws an error Class 'OAuth' not found.

OAuth is installed on my system and code works perfectly out side laravel but when i place code inside of a Laravel controller it throws the error

following is my code of OAuth call that i am making from laravel

$oAuth = new OAuth($integratoinData->auth_data->consumer_key, $integratoinData->auth_data->consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
        $oAuth->setToken($integratoinData->auth_data->access_token, $integratoinData->auth_data->access_token_secret);

        $oAuth->fetch($integrationCredentials['url']);

        $responseInfo   = $oAuth->getLastResponseInfo();

please help me thank you in advance



via Chebli Mohamed

Type casting using string for type

I have table settings with columns: value - varchar type contains setting value and type - enum type contains variable types "int", "string", "float". How can I use string from type column to cast value to this type?

I'm trying to do it in my model but it doesn't work:

public function getValueAttribute($value){
    return ($this->type)$value;
}



via Chebli Mohamed

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 Chebli Mohamed

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 Chebli Mohamed

Laravel datatables - Max execution time exceeded

i use laravel datatables serverside to get data from 4 tables and display them. The code that i have on routes/web.php is:

    Route::get('/serverSideSymv', [
    'as'   => 'serverSideSymv',
    'uses' => function () {
        $symv = App\Symvolaia::Select('table1.*')
            ->join('table2', 'table1.field1', '=', 'table2.id')
            ->join('table3', 'table1.field2', '=', 'table3.id')
            ->leftJoin('table4', function($join)
           {
               $join->on('table1.field3', '=', 'table4.field5');
               $join->on('table1.field6', '=', 'table4.field7');
           })
            ->select('table1.id','table2.field1','table1.field2','table1.field3','table1.field4','table3.field5','table1.field6','table1.field7','table1.field8','table4.field9','table1.field10','table1.field11','table1.field12','table1.field13','table1.field14','table2.field15');
        return Datatables::of($symv)
            ->editColumn('field5', function($data) {
                return Illuminate\Support\Facades\Crypt::decrypt($data->field5);
            })
            ->make();
    }
]);

The issue is that the main table (Table1) has more than 20.000 records and will have much more. I get max execution time exceeded. Is there any way to optimize the query or somehow show the results in datatables?



via Chebli Mohamed

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 Chebli Mohamed

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 Chebli Mohamed

Printing json in Laravel templates

I'm having trouble in moving Eloquent data to Laravel templates as JSON. The problematic data is user inputted text which has linebreaks, all kinds of special characters, quotes, hyphens, MS Word xml garbage tags, you name it.

When I print it to the template as

<script>App.data = JSON.parse('')</script>

I get all kinds of JSON parsing errors. Usually from linebreaks, but also from special characters and so on. I'm now getting rid of them by ugly hacks, like

$data->body = str_replace("\n", "\\n", addslashes($data->body))

But there has to be a more elegant solution. Using the regular json_encode() leaves linebreaks etc in the JSON that end up as errors.

I'm using Laravel 5.3.



via Chebli Mohamed

Laravel searching on hasone relationship

I want to be able to perform search on values in hasOne relationship.

I have deliverables and deliverable_versions table with hasMany relationship. So a deliverable can have many deliverable_versions.

I also have deliverable hasOne deliverable_version to get the latest version.

I want to be able to list the deliverables, but after performing a search on the latest version.

The problem is, in my current database, the versions have all the information needed in search.

So for example, I want to search on the values on "recent version" like this.

$deliverables = $account->deliverables()->with('recentVersion');
$deliverables = $deliverables->search($search); //<--Search on recent version
$deliverables = $deliverables->paginate(4);

How can I achieve something like this in Laravel Eloquent?

Any help is appreciated.



via Chebli Mohamed

Laravel Auto-Link library

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

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



via Chebli Mohamed

Echo file URL from Laravel storage

Im using this code in my laravel view to echo a files path, but its coming up in chrome dev tools with a 404 response.

<img src="">

which echos this onto the page

http://localhost:8000/storage/public/bd0e2f7f.png

The file lives there and this is the correct name for the file so im not entirely sure why its coming up with a 404!



via Chebli Mohamed

Laravel hasMany with multiple constraints

I have query that I run on my ServiceController

return Service::with('contacts', 'locations.datetimes')->find($service->id);

This works great perfectly, but I need to change it. The relationships are defined as follows:

class Service extends Model
{
  public function locations()
  {
    return $this->belongsToMany('App\Models\Service_location', 'service_location_service');
  }
}

class Service_location extends Model
{
  public function datetimes()
  {
    return $this->hasMany('App\Models\Service_detail');
  }
}

I need a second constraint on the datetimes where I need the relationship to be along the lines of

return $this->hasMany('App\Models\Service_detail')->where('service_id', $service->id);

The problem is I can't find a way to pass through the $service_id. How do you handle two constraints on a hasMany relationship?



via Chebli Mohamed

Binding routes to wrong method controller

I am using laravel 5.1 app. I have the bellow routes:

Route::get('{thing}', 'DisplayController@showThingNewRoute');
Route::get('{about}', 'DisplayController@showAboutNewRoute');

Also I use RouteServiceProvider like so:

    public function boot(Router $router)
    {

    parent::boot($router);

    $router->bind('thing', function($thing){ 
       return \App\Thing::publish()->where('seo_url', '=', $thing)->first(); 
   }); 

    $router->bind('about', function($about){ 
       return \App\About::publish()->where('seo_url', '=', $about)->firstOrFail(); 
    });    

    }

The problem is that I can't have a route to execute with a second method showAboutNewRoute

What am i doing wrong here?



via Chebli Mohamed

Passing index value from select to inside php block in one page html

I have two select dropdown. Example:If i select index 3 in the first select option,the display of the 2nd select option should stop at index 3.What is the best way of doing it.See my current code below.

<label class="control-label">SY1:</label> 
<select class="form-control" name="pri_sy" id="pri_sy" onchange="">
<?php 
    $null = 'Null';
    $choose = 'Choose School Year';
    $Present = 'Present';
    echo '<option value='.$null.'>' .$choose.'</option>';
    echo '<option value='.$Present.'>' .$Present.'</option>';
    for($i=date('Y');  $i > date('Y')-27; $i--){
        $x = $i +1;
        $y = $i;
        echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
    }?>
</select>

Result: 
[0]Choose School Year
[1] Present
[2] 2017-2018
[3] 2016-2017   if selected index[3] / How can i pass 3 in my 2nd for loop?
   2015-2016   for($i=date('Y');  $i > date('Y')-3; $i--)/See below php code..
[5]2014-2015
[6]2013-2014
and so on ...



<label class="control-label">SY2:</label> 
    <select class="form-control" name="sec_sy" id="sec_sy" onchange="">
    <?php 
        $null = 'Null';
        $choose = 'Choose School Year';
        $Present = 'Present';
        echo '<option value='.$null.'>' .$choose.'</option>';
        echo '<option value='.$Present.'>' .$Present.'</option>';
        for($i=date('Y');  $i > date('Y')-3; $i--){
            $x = $i +1;
            $y = $i;
            echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
        }?>
    </select>

Expected Result:
Choose School Year
Present
2017-2018
2016-2017    
2015-2016



<script type="text/javascript">

$('.form-control').on('change', function(e) {
  var pri_sy = $("#pri_sy").find("option:selected").index();
  var sec_sy   = $("#sec_sy").find("option:selected").index();
  var sen_high_sy = $("#sen_high_sy").find("option:selected").index();
  var college_sy = $("#college_sy").find("option:selected").index();

  var isPri = $(this).is("#pri_sy");
  var isSec = $(this).is("#sec_sy");
  var isSenHigh = $(this).is("#sen_high_sy");
  var isCollege = $(this).is("#college_sy");
  //console.log("from:"+fromIdx,"to:"+toIdx);
  if (isPri) {
    alert('a');
    $('#sec_sy').val(pri_sy);
    alert(pri_sy);
       // $('#sec_sy').each(function(pri_sy, sec_sy) {     
      // $(sec_sy).attr('disabled', pri_sy < sec_sy);
     });
  }  
}).change();
</script>



via Chebli Mohamed

laravel cron job windows

Iam trying to develop a cron job for a command to send email. I am completely new to cron jobs so I dont really know how it works.

Trying the command by myself in the console works perfectly. But when a set a cron job in CPANEL its not workingrs. I am using Laravel 5, can anyone help please?

Thanks!

My cron job: php /home/reporting/public_html/bsk/artisan schedule:run >> /dev/null 2>&1

My Kernel.php

Kernel.php

MY class emailUser

emailUser class



via Chebli Mohamed

Send additional parameters to Stripe with Laravel Cashier

The Laravel docs states how to send extra parameters to Stripe like email. My question is how to send other parameters like adress and name. Below is some of the customer.updated webhook.

"sources": {
  "object": "list",
  "data": [
    {
      "id": "card_1A3KXJUybOxa5viznC3iZy5U",
      "object": "card",
      "address_city": null, 
      "address_country": null,
      "address_line1": null,
      "address_line1_check": null,
      "address_line2": null,
      "address_state": null,
      "address_zip": null,

And in my Laravel controller..

 $user->newSubscription('Silver', 'Silver')->create($creditCardToken, [
       'email' => $request->input('email'),
       'description' => 'Silver membership'
 ]);

The above works fine to send email and description to Stripe. But 'adress_city' => 'New York' for example doesn't.



via Chebli Mohamed

Exception in Collection.php line 1527: Property [id] does not exist on this collection instance

i m getting error Exception in Collection.php line 1527: Property [id] does not exist on this collection instance.

public function index()
    {
        $response=array();
        $data = MyList::all();
        $response['id']=$data->id;
        $response['name']=$data->name;
        $response['password']=$data->password;
        $response['city']=$data->city;   
        return ResponseClass::prepareResponse(
                    $response,
                    'success',
                    ''
                );
    }



via Chebli Mohamed

Apply Middleware to all routes except `setup/*` in Laravel 5.4

I'm experimenting with Middleware in my Laravel application. I currently have it set up to run on every route for an authenticated user, however, I want it to ignore any requests that begin with the setup URI.

Here is what my CheckOnboarding middleware method looks like:

public function handle($request, Closure $next)
{
    /** 
    * Check to see if the user has completed the onboarding, if not redirect.
    * Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
    */
    if ($request->user()->onboarding_complete == false && $request->path() != 'setup') {
        return redirect('setup');
    } else {
        return $next($request);
    }
}

This is being used in my routes like this:

Route::group(['middleware' => ['auth','checkOnboarding']], function () {
    Route::get('/home', 'HomeController@index');
    Route::get('/account', 'AccountController@index');

    Route::group(['prefix' => 'setup'], function () {
        Route::get('/', 'OnboardingController@index')->name('setup');
        Route::post('/settings', 'SettingsController@store');
    }); 
});

Now, if I go to /home or /account I get redirected to /setup as you would expect. This originally caused a redirect loop error hence why & $request->path() != 'setup' is in the Middleware.

I feel like this is a really clunky way of doing it, and obviously doesn't match anything after setup like the setup/settings route I have created.

Is there a better way to have this Middleware run on all routes for a user, but also set certain routes that should be exempt from this check?



via Chebli Mohamed

Get authorization Form Lumen ( Laravel micro framework) header From Laravel

In project , all API's call from Lumen. Front is developed in Laravel. We are calling Lumen APIs using Guzzle http client guzzleHttp .

Now, I need to set header Authorization for all API calling so I'm sending token in header from laravel but in Lumen I can't get token in Lumen request header.

below is the example code. :

Laravel Controller Code

public function get_category(){


    $accessToken = 'kjdhfdkjfhdkjfhfjkdf9875443213456';


    $response = \Guzzle::request("GET","example.com", "categories",['headers' => [
        'Authorization' => $accessToken
    ]]);

    $category_all = json_decode($response->getBody()->getContents(),true);

    return $category_all;

}

Lumen Middleware Code. :

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

   dd($request);

}

In Lumen request I can't get token in request header.

any help will be thankful.



via Chebli Mohamed

jeudi 30 mars 2017

Queue mails through Laravel 5 scheduler

I have a scheduler set up to run every minutes:

$schedule->command('reminder_upcoming_tasks')
         ->everyMinute();

Which is suppose to queue an email:

Mail::to($user->email)
    ->queue(new ReminderUpcomingTasksMail($user));

Unfortunately this doesn't work but using notification instead works:

Notification::send($user, new ReminderUpcomingTasksNotification($user));

So I know that my scheduler works and is properly triggered.

And my Mail looks like this:

<?php

namespace App\Mail;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ReminderUpcomingTasksMail extends Mailable
{
    use Queueable, SerializesModels;

    protected $user;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user               = $user;
        $this->onQueue('default');
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.reminder_upcoming_tasks')
            ->with([
                'user'               => $this->user,
            ])
            ->subject("Your daily summary");
    }
}

If I test this mail in a controller without queue, this also works:

Mail::to($user->email)
    ->send(new ReminderUpcomingTasksMail($user));

Any idea of what's missing?



via Chebli Mohamed

It is possible to run multiple instance of foundation-emails?

I am working on an web app to build newsletters email, I wanna use foundation-emails but I dont know if is possible to run multiple instances for build multiple email.

For example, two user use the web app and build emails at the same time.

The output must be an html file and its assets (images and files), all this in a zip.

Thanks in advance.

foundation-emails



via Chebli Mohamed

Upgrading To 5.4.0 From 5.1 laravel

I am using 5.1 laravel version and I would like to know like to upgrade to the latest version of laravel which is 5.4.

Can we directly Upgrading To 5.4 From 5.1 laravel ?



via Chebli Mohamed

Laravel Middleware & Service Provider flow

I have a Laravel 5.4 app where I set the Locale of the app in a middleware, depending on the root domain, because I have a domain for each language. This is because of SEO & Adwords stuff, I can't change that.

Secondly I have a ViewComposerServiceProvider where I prepare Data for the Layout View. This data depends on the Language, but the language hasn't been set yet, because the ServiceProvider is executed first.

What should I do?



via Chebli Mohamed

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 Chebli Mohamed

Laravel 5.4 - Use Controller Route in javascript function

I have a table (datatables) and I have an edit icon and I want to call a route with the parameter.

My function is currently is

function editItem(id)
    {
        //alert(id);
    }

What I want to do is to call

UsersController@editItem

and also pass the id to the controller.

I am a little stuck!



via Chebli Mohamed

Dynamically display JSON object in descending order in blade template

I'm trying to display a JSON object in descending order that is returned to my blade template that should look the output below

2007 | 30 | 28 | 5 | 2 | -10
2008 | 55 | 43 | 23 | 0.5 | -1

JSON looks like this

{
    "2007":{
        "number-xx" : "5",
        "number-aa" : "30",
        "number-ef" : "2",
        "number-sa" : "-10",
        "number-ab" : "28",
    },
    "2008":{
        "number-xx" : "-1",
        "number-aa" : "0.5",
        "number-ef" : "23",
        "number-sa" : "55",
        "number-ab" : "43",    
    }
}

So far I have something like this that shows the year and the numbers if I manually declare them so I can't really set it in descending order.

@foreach ($data['quilt_data_obj'] as $year => $obj)
     |  |  |  |  | 
@endforeach

But I'm just not sure how I can get it to show the numbers dynamically in descending order in my blade template.

Any guidance would be appreciated. Thank you!



via Chebli Mohamed

Laravel 5.4 Script loading issue

I'm working on my first Laravel project (5.4), actually I don't understand why my js script doesn't work like I expected. I use Mix and Blade :

// webpack.mix.js
let { mix } = require('laravel-mix').mix;

    // copy fonts and patterns
mix .copy('resources/assets/vendor/bootstrap/fonts', 'public/fonts')
    .copy('resources/assets/vendor/font-awesome/fonts', 'public/fonts')
    .copy('resources/assets/patterns', 'public/css/patterns')

    // compile scss and concatenate css files
    .sass('resources/assets/sass/app.scss', 'public/css')
    .styles([
        'resources/assets/vendor/bootstrap/css/bootstrap.css',
        'resources/assets/vendor/animate/animate.css'
        // ...
    ], 'public/css/vendor.css')

    // concatenate js files
    .js([
        'resources/assets/vendor/jquery/jquery-3.1.1.min.js',
        'resources/assets/vendor/bootstrap/js/bootstrap.js',
        'resources/assets/js/app.js'
        // ...
    ], 'public/js/app.js')
    .options({ processCssUrls: false }); // fix for path issue : http://ift.tt/2noncIN

After npm run dev compliation looks good :

DONE  Compiled successfully in 6497ms                                                     4:20:57 PM

                                   Asset      Size  Chunks                    Chunk Names
  fonts/glyphicons-halflings-regular.ttf   45.4 kB          [emitted]         
                              /js/app.js    1.2 MB       0  [emitted]  [big]  /js/app
                       mix-manifest.json  66 bytes          [emitted]         
  fonts/glyphicons-halflings-regular.eot   20.1 kB          [emitted]         
fonts/glyphicons-halflings-regular.woff2     18 kB          [emitted]         
  fonts/glyphicons-halflings-regular.svg    109 kB          [emitted]         
 fonts/glyphicons-halflings-regular.woff   23.4 kB          [emitted]         
                            /css/app.css    178 kB       0  [emitted]         /js/app
           fonts/fontawesome-webfont.ttf    166 kB          [emitted]         
           fonts/fontawesome-webfont.svg    444 kB          [emitted]  [big]  
           fonts/fontawesome-webfont.eot    166 kB          [emitted]         
          fonts/fontawesome-webfont.woff     98 kB          [emitted]         
         fonts/fontawesome-webfont.woff2   77.2 kB          [emitted]         
                   fonts/FontAwesome.otf    135 kB          [emitted]         
         css/patterns/header-profile.png   5.88 kB          [emitted] 

CSS works fine, bootstrap.js also works and when I check inside /js/app.js it seems like everything is inside.

An here is my tempate :


<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{!! asset('css/vendor.css') !!}" />
    <link rel="stylesheet" href="{!! asset('css/app.css') !!}" />
</head>
<body>
    <!-- Main view  -->
    @yield('content')

    <script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>

    @section('scripts')
    @show
</body>
</html>

My troubles began when I want to add a script inside the script section from a child.

@extends('layouts.app')

@section('scripts')
    <script type="text/javascript">
        $(document).ready(function () {
            alert('test');
        });
    </script>
@endsection

I got Uncaught ReferenceError: $ is not defined like if jquery wasn't loaded.

I have no clue why, any idea ?

[note]
It works if I replace inside app.blade.php :

<script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>

with :

<script src="http://ift.tt/1pCaG3c"></script>
<script src="http://ift.tt/2aHTozy"></script>



via Chebli Mohamed

Displaying JSON object on blade template

I'm trying to display a JSON object that is returned to my blade template that should look the output below

2007 | Kanye | UltralightBeam  
2008 | JayZ  | 99 Problems

JSON looks like this

{
    "2007":{
        "name" : "Kanye",
        "song" : "UltralightBeam"
    },
    "2008":{
        "name" : "JayZ",
        "song" : "99 Problems"        
    }
}

So far I have something like this that shows the name and song

@foreach($data['data_obj'] as $obj)
     |  
@endforeach

But I'm just not sure how I can get it to show the year as well?

Any guidance would be appreciated. Thank you!



via Chebli Mohamed

laravel request - combine rules with or operator

I was wondering if in laravel 5.4 you can combine multiple request rules with OR operator instead of the AND.

For example: if ou want to write a request rule for a number and you want that number to be required and alpha num you will do something like that:

'number' => 'required|alpha_num',

But let's say that you want the number field to have or alpha_num of alpha_dash or CustomValidator. something like that

'number' => 'required|(alpha_num or alpha_dot or customValidator)',

for the second rule (with the alpha..) if any matche is found the request is true. It's more like an OR operator than a AND with the |. I want at least one match Thank you for your help



via Chebli Mohamed

Function MYSQLI_ASSOC Laravel 5.2

I have this function that should translate into laravel 5, how can I do?

public function query_while($resource)
    {
           $result = $this->query($resource);
                $Return = $result->fetch_array(MYSQLI_ASSOC);
                $result->close();
                return $Return;

    }

Thk John



via Chebli Mohamed

Laravel spark installation npm dependency issue

While installing spark, reaching at the point of installing dependencies when I say yes, it hangs on following error - "npm WARN deprecated node-uuid@1.4.8: Use uuid module instead"

I am looking for a workaround for same.



via Chebli Mohamed

Laravel logging out on user deleting

I am using Laravel 5.3.

I have an User model extending Authenticatable.

I also have an users panel where the super user can update and delete other users.

However, every time the super user deletes another user, he gets disconnected (logged out) from the system. How can I workaround this?



via Chebli Mohamed

laravel 5.4: PHP Fatal error: Call to undefined method Illuminate\Foundation\Application::configure()

I am new to laravel. I am trying to use Snappy PDF from barryvdh. I have installed snappy pdf by following instruction from http://ift.tt/1zu8XUG. But when i run php artisan serve command following error is showed

PHP Fatal error: Call to undefined method Illuminate\Foundation\Application::configure() in F:\xampp\htdocs\Laravel\doctorApp\vendor\barryvdh\laravel-snappy\src\LumenServiceProvider.php on line 21

Here is that line from my LumenServiceProvider.php:

public function register()
{
   $this->app->configure('snappy'); // line 21

   $configPath = __DIR__ . '/../config/snappy.php';
   $this->mergeConfigFrom($configPath, 'snappy');
}

I have installed wkhtmltopdf using this:

$ composer require h4cc/wkhtmltopdf-amd64 0.12.x
$ composer require h4cc/wkhtmltoimage-amd64 0.12.x

in config/app.php i have added follwing lines in my providers and aliases:

in providers: Barryvdh\Snappy\ServiceProvider::class,

in aliases:

'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,

The path to the binaries in my config file (config/snappy.php): first one for pdf..

'binary' => base_path('vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'),

2nd one for image...

'binary' => base_path('vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64'),

my bootstrap/app.php:

<?php

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

/*snappy pdf start--- i added this part*/
class_alias('Barryvdh\Snappy\Facades\SnappyPdf', 'PDF');
$app->register(Barryvdh\Snappy\LumenServiceProvider::class);

//Optionally, add the facades like so:

class_alias(Barryvdh\Snappy\Facades\SnappyPdf::class, 'PDF');
class_alias(Barryvdh\Snappy\Facades\SnappyImage::class, 'SnappyImage');

/*snappy pdf end*/


$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);


return $app;

In my controller i added:

use Barryvdh\Snappy\Facades as PDF;

This is my controller:

public function PdfView(Request $request, $patient_id)
{
   $patients = Patient::where('id', $patient_id)->first();
   $pdf = PDF::loadView('pdfview', ['patients'=>$patients]);
   return $pdf->download('pdfview.pdf');

}

Can someone please say, why this error occurred and how to resolve this?



via Chebli Mohamed

array to string conversion in laravel

I am trying to fetch some data from table in laravel 5.0 like so

 <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
 {!! $moduleCategories = DB::table('module_categories')->select('categories_name')->where('modules_id','=',$modules->id)->get() !!}
 @foreach($moduleCategories as $category)
     <a class="dropdown-item" href="#"></a>
 @endforeach
 </div>

$module->id is obtained from another query result. Now when I try to run this I am getting Array to string conversion. Can someone point out the mistake. The expected output is > 1 in the sense there can be multiple categories names matching that condition.



via Chebli Mohamed

php artisan commands: Out of memory

I get the following error messages after waiting about ~10 sec when using the following laravel command (The out of memory error appears in any other php artisan command aswell):

php artisan make:controller CardController --resource

What can go wrong? I already used laravel before and everything worked fine.

c:\xampp\htdocs\my-server>php artisan make:controller CardController --resource

VirtualAlloc() failed: [0x00000008] Not enough storage is available to process this command.


VirtualAlloc() failed: [0x00000008] Not enough storage is available to process this command.

PHP Fatal error:  Out of memory (allocated 1587544064) (tried to allocate 402653192 bytes) in C:\xampp\htdocs\my-server\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 579

Fatal error: Out of memory (allocated 1587544064) (tried to allocate 402653192 bytes) in C:\xampp\htdocs\my-server\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 579



via Chebli Mohamed

sudo composer install vs. composer install

I run sudo composer install I got this warning

Do not run Composer as root/super user! See http://ift.tt/1UioBPp for details

I tried just composer install I got this error

[ErrorException] file_put_contents(/Applications/MAMP/htdocs/code/bheng/vendor/composer/installed.json): faile d to open stream: Permission denied

Here is the current permission set on my Laravel folder

total 1872
-rw-r--r--   1 bheng  staff     777 Feb 27 20:18 phpunit.xml
-rw-r--r--   1 bheng  staff      87 Feb 27 20:18 phpspec.yml
-rw-r--r--   1 bheng  staff     481 Feb 27 20:18 package.json
drwxr-xr-x   3 bheng  staff     102 Feb 27 20:18 note
-rw-r--r--   1 bheng  staff     967 Feb 27 20:18 md-bheng-readme.txt
-rw-r--r--   1 bheng  staff     503 Feb 27 20:18 gulpfile.js
-rw-r--r--   1 bheng  staff      26 Feb 27 20:18 contributors.txt
-rw-r--r--   1 bheng  staff    1635 Feb 27 20:18 artisan
-rw-r--r--   1 bheng  staff      43 Feb 27 20:18 Procfile
-rw-r--r--   1 bheng  staff    5634 Feb 27 20:18 Gruntfile.js
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 tests
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 storage
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 sql
-rw-r--r--   1 bheng  staff     560 Feb 27 20:18 server.php
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 resources
-rw-r--r--   1 bheng  staff     105 Feb 27 20:18 pull.sh
drwxr-xr-x   7 bheng  staff     238 Mar  1 14:46 bootstrap
-rw-r--r--@  1 bheng  staff       0 Mar  1 14:46 Icon?
drwxr-xr-x  22 bheng  staff     748 Mar  2 11:47 app
drwxrwxrwx@ 27 bheng  staff     918 Mar  3 14:55 public
drwxr-xr-x   8 bheng  staff     272 Mar  6 13:25 database
-rw-------@  1 bheng  staff     405 Mar 14 09:29 id_rsa.pub
-rw-------   1 bheng  staff    1766 Mar 14 09:29 id_rsa
-rw-r--r--   1 bheng  staff  126713 Mar 14 10:00 composer.lock
drwxr-xr-x  18 bheng  staff     612 Mar 28 21:24 config
-rw-r--r--   1 bheng  staff    1022 Mar 30 12:21 composer.json
drwxr-xr-x  32 bheng  staff    1088 Mar 30 12:21 vendor


How do I fix this ? Do I need to chmod any folders ?



via Chebli Mohamed

Laravel Auth::attempt always return false?

Here is myscreen shot of database and my login input enter image description here

public function action(Request $request){
         $username = $request->username;
         $pass = bcrypt($request->password);
         $credentials = [
                         'id' => $username,
                         'password' => $pass
                        ];

    dd(Auth::attempt($credentials));
         if (Auth::attempt(['id' => $username, 'password' => $pass])) {
            echo 'Ok';
         }else{
            echo 'Not ok';
         }

I'm trying to make a login action using laravel auth::attemptbut it always return false.



via Chebli Mohamed

Eager loading relationship returns empty using SELECT in WITH clause

Using Laravel 5.4, I have a query that correctly returns a relationship. Using the "with" clause in the query, I am attempting to return only selected columns from the relationship in my controller.

When I add the select to the with clause, relationship returns an empty array. Oddly enough, if I add a different parameter, such as a groupBy or join the query DOES return results. So something about my setup dislikes the select on the query.

Thus far I have tried:

  • using selectRaw
  • using select(DB::raw)
  • tried defining this as a separate relationship on my model.

Nothing has worked this far. Sql log looks good when I dump it.

Here is my model:

// MODEL
namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class ClassBlocks extends Model
{
    public $timestamps = false;

    public function schedule(){
        return $this->hasMany('App\ClassSchedules', 'class_block_id', 'id');
    }
}

And here is my controller:

//CONTROLLER
use App;
use DateTime;
use Illuminate\Http\Request;

class ProgramsController extends Controller
{
    public function filterClass(Request $request, App\ClassBlocks $block)
    {

        $block = $block->newQuery();

        // Attempt to eager load relationship
        // Returns results when "select" disabled
        $block->with([
            'schedule' => function($query){
                $query->select('time_start');
                $query->groupBy('day');
            },
        ]);

        return $block->get();

    }
}

Here is a sample result with select enabled (schedule returns empty):

[
  {
    "id": 13,
    "program_id": "1",
    "class_group_id": "1",
    "schedule": [

    ]
  }
]

And here is a result with select disabled (returns relationship when select disabled):

[
  {
    "id": 13,
    "program_id": "1",
    "class_group_id": "1",
    "schedule": [
      {
        "id": 338,
        "class_group_id": "1",
        "program_id": "1",
        "class_block_id": "13",
        "date": "06/13/2017",
        "day": "Tuesday",
        "instructor_id": "1",
        "time_start": "6:30am",
        "time_end": "6:30am"
      },
      {
        "id": 339,
        "class_group_id": "1",
        "program_id": "1",
        "class_block_id": "13",
        "date": "06/14/2017",
        "day": "Wednesday",
        "instructor_id": "2",
        "time_start": "6:30am",
        "time_end": "6:30am"
      }
    ]
  },
]

Any insight would be greatly appreciated.



via Chebli Mohamed

Laravel Login always return false due to getAuthPassword return null

As per my title mentioned. I can't use auth()->attempt($credentials, false) as it always return false.

After further digging in to the problem, finally found that it was due to this.

public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }

the $user->getAuthPassword() return null even though the $user have password on the original while I dump it out

Does anybody know how this getAuthPassword() work?



via Chebli Mohamed

is laravel cloning my mock object?

Im testing a Soap web service with getMockFromWsdl from phpunit, for unit testing within laravel works fine, but when I try to replace the SoapClient in a feature test, it always fails, like the web service never called, but actually the mock is called.

I suspect that laravel is cloning somewhere my $this->soapClient because if I debug the code, it calls the soap mock and gets what is faked in the mock but always receive the error:

Expectation failed for method name is equal to <string:GetToken> when invoked at least once.
Expected invocation at least once but it never occurred.

My code is like:

public function test_soap_call()
{
    $this->soapClient = $this->getMockFromWsdl(dirname(__FILE__).'/../Mocks/service.wsdl');

    $this->soapClient->expects($this->atLeastOnce())
        ->method('GetToken')
        ->with(['Code' => '03600', 'User' => 'username'])
        ->willReturn(unserialize('O:8:"stdClass":1:{s:26:"GetTokenResult";s:36:"5aae60ec-2bcd-459d-a135-a20eb7c10007";}'));

    $this->app->instance('MySoapClient', $this->soapClient);

    $this->postJson('/api/order', $this->getValidRequest());

}

and in my controller (/api/order) I have

$soap = $this->app->make('MySoapClient');
$soap->GetToken(['Code' => '03600', 'User' => 'username']);

Am I using correctly the Laravel Service Container?

PD: Something similar happened to me, when doing a Spy and using $app->instance, where I was trying to get what was passed to an object, but always got null. I solved it declaring the field of the spy static.



via Chebli Mohamed

How to use group by with multpile columns?

I'm using this query to get data, but problem is that i dont get regions. Any suggestion how can i get regions but to avoid duplicate districts ?

 $data = Districts::distinct('order')->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('district')->groupBy('district')->get();



via Chebli Mohamed

Laravel: Save a hasOne relationship change

I currently have a relationship between checklistItem and actions as followed:

public function action()
{
     return $this->belongsTo(Action::class, 'action_id', 'id');
}

public function checklistItem()
{
     return $this->hasOne(ChecklistItem::class, 'action_id', 'id');
}

I currently made a method, when saving an action, the checklistItem status should also change depending on what was chosen:

public static function saveFromRequest(Request $request)
    {
        if (($action = parent::saveFromRequest($request)) !== null){

            if (!is_null($action->checklistItem)) {
                $action->checklistItem->value->status = $action->switchStatusChecklist($action);

                //Need to update or save this specific checklistItem
                $action->checklistItem->save();
            }
        }

        return $action;
    }

function switchStatusChecklist($action)
    {
        switch($action->status) {
            case 'closed':
                $status = 'checked';
                break;
            case 'canceled':
                $status = 'notapplicable';
                break;
            default:
                $status = 'open';
                break;
        }
        return $status;
    }



via Chebli Mohamed

Laravel redirect issue from blade template

I am new in laravel 5 . I am working on larvel page security and i have to prevent open some page or Url but when i use in view it is not working .

Please help me to find a way to use Redirect / Url in laravel view (Blade template)

I have already tried :- 

1. 
2.  

Thanks all



via Chebli Mohamed

Using distinct or group by?

This is how my table looks like:

enter image description here

Now i have this query for suggestion:

  $data = Districts::distinct()->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();

What i want is that if user enter for example: Kreis 2 to get only one record Kreis 2, in my case it get few of them because Kreis 2 have 3 regions. Any suggestion how can do that?



via Chebli Mohamed

Modifying and using env file in same controller- Laravel

Ok I have a strange problem. My task is to modify env file, add credentials and name of new database and then use it to connect to that database.

my controller code is like this:

        $http = new GuzzleHttp\Client;
        $response = $http->request('POST', 'url to create new database and make entry in env file', [
            'form_params' =>['necessary parameters for new db creation'],
        ]);
        //if i put a dd('ok') here and check env file and database, 
        //env file has been updated with db name, username and pass and 
        //one new database and user has been created as well.

        Artisan::call('config:clear');
        Artisan::call('cache:clear');
        exec('composer dump-autoload');
        sleep(5);

        $database = env('NEWDB_DB_DATABASE','');//''
        $username = env('NEWDB_DB_USERNAME','');//''
        $password = env('NEWDB_DB_PASSWORD','');//''

$database,$username and $password comes out as empty string - "" I dont know what else I should try . I cannot restart server in middle of the script.

Any help is appreciated.



via Chebli Mohamed

Distinct is not working?

  $data = Districts::distinct()->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();

I have this query, but problem is that distinct not working. I get for example three records for same thing. Any suggestion?



via Chebli Mohamed

Laravel save($request->all()) Error

Hello great people of Stackoverflow!

I have a question, I've been developing laravel application and I encountered this strange error:

QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`testenv`.`products`, CONSTRAINT `products_tenant_id_foreign` FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`)) (SQL: insert into `products` () values ())

and Here's my store function

public function store(Request $request)
    {
        $product = new Product;

        /*$product->name = $request->name;
        $product->stockQty = $request->stockQty;
        $product->minimumQty = $request->minimumQty;
        $product->description = $request->description;
        $product->notes = $request->notes;
        $product->tenantMargin = $request->tenantMargin;
        $product->length = $request->length;
        $product->height = $request->height;
        $product->weight = $request->weight;
        $product->showLength = $request->showLength;
        $product->showHeight = $request->showHeight;
        $product->showWeight = $request->showWeight;
        $product->size = $request->size;
        $product->colorName = $request->colorName;
        $product->colorHex = $request->colorHex;
        $product->isActive =$request->isActive;
        $product->tenant_id = $request->tenant_id;
        $product->productviewid = $request->productviewid;*/

        $product->save($request->all());

        return "product successfully created";
    }

And the error only occurs if i use

$product->save($request->all()); but if I un-comment the the commented code and use $product->save() instead, it works, no error.

Can anyone help me to find the source of this problem?



via Chebli Mohamed

how to continue requesting when first response is not accepted in php?

I am a new for using Guzzle package i want to send data via web api when response coming with status OK or NOT i do some action otherwise status equal waiting i request again after 5second or status equal not yet sleep for 30 second. this is my code

$client = new Client();
  $headers= [
            'Accept' => 'application/x-www-form-urlencoded',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        $body = [
            'phone2'=>'723457481',
            'amount'=>'200'
        ];
        $url = "http://ift.tt/2oBhHH4";

       $response = $client->Request("POST", $url, [
            'handler'  => $stack,
            'headers'=>$headers,
            'form_params'=>$body
        ]);
        $contents = (string) $response->getBody();
       // this $contents can be  status 'ok','not' anything

So how can I send again according response status ? Thanks



via Chebli Mohamed

Laravel Eloquent: cherry pick custom attributes

I'm using an API to retrieve my objects in JSON. I have a model which has a lot of computing-intensive custom attributes (for example, sums from other tables in the database). On some pages, I'd like to load a specific set of custom attributes.

If they were relationships, I could use Model::with().

I'm looking for a way to "eager load" my custom attributes. For performance reasons, I don't want to add them to the model's $append list.



via Chebli Mohamed

TokenMismatchException on some AJAX calls

When I send many fast async AJAX request (because I have a filter for a DataTable) to one of my controllers sometimes I get a TokenMismatchException.

I rewrite the tokensMatch method of the VerifyCsrfToken middleware to check what's happen, but I can't figure out.

protected function tokensMatch($request) {

    $sessionToken = $request->session()->token();

    $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

    if (!$token && $header = $request->header('X-XSRF-TOKEN')) {
        $token = $this->encrypter->decrypt($header);
    }

    if (!is_string($sessionToken) || !is_string($token)) {
        return false;
    }

    $areEquals = hash_equals($sessionToken, $token);

    if (!$areEquals ) {
        //////////// Sometimes $sessionToken and $token are not equals.
        //////////// $sessionToken have a different value than the current ANTI-CSRF token.
        dd($sessionToken." - ".$token);
    }

    return $areEquals;
}

The problem I see is which $sessionToken is different than $token (the token I have send on the X-CSRF-Token header).

I set this request header as follow:

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        //////////// Only for my domain (I have commented this line; But it is not the cause of the issue) 
        if (settings.url.indexOf(document.domain) >= 0) {
            //////////// The #X-CSRF-TOKEN is updated every five minutes. 
            //////////// But it is not the cause of the issue too, 
            //////////// because sometimes it works, sometimes it does not —I do not understand the reason— and then it does it again (without changing the token)...
            xhr.setRequestHeader("X-CSRF-Token", $("#X-CSRF-TOKEN").val());
        }
    }
});

By the way, I moved all the web middleware's to $middleware from $middlewareGroup... But I thinkg this is not the cause of the issue; because before move those middlewares it also happened...

Any idea what may be happening?


My Laravel version is 5.2.45



via Chebli Mohamed

Will Laravel 5.4 run on PHP 5.6.3?

I know that laravel 5.4 need to meets PHP >= 5.6.4. I try to find XAMPP with php 5.6.4 but i have nothing. I just have xampp with php 5.6.3 installed. Will laravel 5.4 run on php 5.6.3?



via Chebli Mohamed

whereraw Vs DB::raw in Laravel

I am confused and really don't know how and where should I choose to use one from both ?

I read docs for both

http://ift.tt/2ny0L4A

And

http://ift.tt/2nOmc3I

If I use query something like this its not working

DB::table('table_name')
->where('parent_id', $parent_id)
->whereRaw("date",">",$date)
->get();

But it works

DB::table('table_name')
->where('parent_id', $parent_id)
->where(DB::raw("date",">",$date))
->get();



via Chebli Mohamed

Laravel Eloquent query not working

the below query is working in SQL but when i tried in eloquent not getting expected data

// SQL working
SELECT id,first_name,last_name,phone_number,registration_id FROM drivers WHERE first_name LIKE "A%" ORDER BY first_name ASC LIMIT 5 OFFSET 0


//Laravel eloquent, result not as expected, getting all the data with limit of 5
    public function getSearchList($alphabet, $limit)
    {
        //dd($alphabet, $limit);
        $drivers = Driver::select('id','first_name','last_name','phone_number','registration_id')
                   ->where('first_name', 'like', '%'.$alphabet.'%')
                   ->orderBy('first_name', 'asc')
                   ->limit(5)->offset($limit)
                   ->get();

        if (count($drivers) == 0) {
            return $this->respondNotFound();
        }

        return Response::json([
            'data' => $drivers->all()
        ]);
    }

thank you



via Chebli Mohamed

Laravel middleware doesn't store the session value

I try to put my language in session(), but when I check session: dd(session()->get('locale')); - it's null. I have no idea why. I need to store that value in session.

my middleware:

class LangSwitch {
...
public function handle(Request $request, Closure $next)
        if(!session()->has('locale')){
            $locale = $request->segment(1);
            session()->put('locale', $locale);    
        }
        else{
            $locale = session()->get('locale');
        }

        if (!array_key_exists($locale, Config::get('app.locales'))) {
            $segments = $request->segments();
            $segments[0] = Config::get('app.fallback_locale');

            return redirect()->to(implode('/', $segments));
        }

        App::setlocale($locale);

        return $next($request);
    }
}

my kernel:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\LangSwitch::class,
    ],



via Chebli Mohamed

Laravel command interface is auto exiting after i type php composer.phar

Whatever i type that is a command in composer documentation. It runs but the command line is auto exiting. So after entering the command i immediately tried to screenshot what the command outputs and then it will automatically close.

So the problem here is. How can i make the command line stay and won't exit so i can use the command line effectively?

Here's the photo of my screenshot:



via Chebli Mohamed

nginx root directory for laravel

I would be very grateful if someone could answer. I am trying to install my laravel project to virtual host. The server runs on nginx. Everything is ok except assets file.

The problem is the server does not load assets files. To be more exact:

asset()

function doesnt point to public path.

But the URLs (routes) are working perfect.

I copied htaccess files from public path to root.

Here is my htaccess files content:

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

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

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

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

Any helps guys! Thank you very much!



via Chebli Mohamed

mercredi 29 mars 2017

Laravel Query Builder Sub-Queries - orderBy, groupBy

How can I convert the below query to query builder format in Laravel 5.3:

$query =   "SELECT *
    FROM (
        SELECT * FROM $table1
        WHERE msgNew=1
        ORDER BY msgDate DESC
    ) x
GROUP BY msgGroup
ORDER BY msgDate DESC
LIMIT 0, 10";

$results = DB::select($query);

Looking to convert it to:

$results = DB::table($table1)
    ->orderBy('msgDate', 'DESC')
    ->.....etc....
    ->groupBy('msgGroup')
    ->.....etc....
    ->get();



via Chebli Mohamed

Generating URL specific routes in a multi-URL Laravel application

I have multiple URLs going to a single Laravel application:

  • www.mydomain.com
  • panel.mydomain.com

Within this I have several routes configured:

<?php
Route::group(['middleware' => ['web']], function () {
    Route::get('/page', 'App\MyApp\Page\Controllers\PageController@index')->name('home');
});

Route::group(['middleware' => ['web'], 'domain' => 'panel.mydomain.com'], function() {
    Route::get('/page', 'App\MyApp\Page\Controllers\ControlPanelPageController@index')->name('controlpanel.dashboard');

});

So anyone going on panel.mydomain.com gets a ControlPanelPageController index method, everyone else gets the PageController method.

However I'm having difficulty generating a link from a named route.

For example:

<?php
namespace App\MyApp\Page\Controllers;
use App\Http\Controllers\Controller;

class ControlPanelPageController extends Controller 
{
    public function index()
    {
        echo route('home');
        // output: /page
        echo url( route('home') );
        // output: http://ift.tt/2nx65pb

        // required output: http://ift.tt/1G4ROBG
    }


}



via Chebli Mohamed

Last entry on join table

I've two table "questionnaires" and "question" link by the table "question_questionnaire". I want to retrive all questions of the last questionnaire with questionnaire.cible="personnel". I'm using laravel 5.3.

I've tried this but it doesn't work :

DB::table('questions')
 ->join('question_questionnaire','question_questionnaire.question_id','=','questions.id')
 ->join('questionnaires','questionnaires.id','=','question_questionnaire.questionnaire_id')
 ->orderBy('questionnaires.created_at','desc')
 ->first()->where('questionnaires.cible','=','personnel')->get();

Could you help me?



via Chebli Mohamed

How to run Laravel queued jobs automatically

In Laravel, Jobs are Queued to run in order, or in the background, at a later time. I use this for processor intensive tasks like audio conversion, which the user doesn't necessarily have to sit around and wait for each time they upload a file.

Queued jobs are run with the command php artisan queue:listen - but is there a way to run the queue from php code, or set each job to run instantly?

If the server is restarted and the command php artisan queue:listen is not run, jobs can build up and never be run - it would be nice to have control within the application.

Laravel docs hint that 'Queue::' can be used to control certain queue commands http://ift.tt/2nhMcAo



via Chebli Mohamed

Retrive data from database in Laravel 5.0

I have a table in my database called modules so in my controller I write like this to retrieve datas from the table

 $allModuleNames = DB::table('users')->get();
 return view("BaseView.home")->with('$allModuleNames',$allModuleNames);

But for some weird reason I am getting syntax error, unexpected ';' error on the query like. This must be silly I guess,not able to pass through this. Can someone help?



via Chebli Mohamed

Is laravel 4.2 safe?

Guys I've been struggling the past few days to upgrade my project from L4.2 to 5.0, but it came in my mind what's the point from upgrading the project to L5? All I care about is the security risks, so since my project is working very well with L4.2 is there is any risks or is it okay ?

thanks



via Chebli Mohamed

Laravel serve on sub domain routing

I use php artisan serve for the dev server. I came across a situation where I had to implement sub domain routing. Lets say the domain I provided is admin.myapp.com , is there any way that I can use the serve command to access the url in my local machine? I have multiple sub domains in the laravel application.
I know one possibility is to create a local virtual host in apache/nginx and update the url in /etc/hosts. I am using ubuntu 14.04 and laravel 5.2



via Chebli Mohamed

decrypt random error with Laravel's built-in encryption facilities

I send invitation by mail to users with a encrypted email to know which user respond to invitation. Something like:

Hello, click on this link to start learning: http://ift.tt/2oyyxpH

The encrypted email is the long string above. I encode mail like this in a Mailable class:

$url = 'http://ift.tt/2nM3qdd' . encrypt($this->to[0]['address']);

Then this $url is added in a mail template like this:

<a href=">click me<a>

Then, when user clicks the link, it routes to a controller and the controller decrypts the payload:

decrypt($request->input('e'));

Then, it works for about 99% of people clicking link. But for about one percent, it does not work, I have an error decrypting. And I don't know why. This is the same Laravel application which encrypts and decrypts. Is there an reason for such a weird behavior?

Side note: I know decrypt always work and has not a random behavior. I tested it on 10000 entries, it's OK. There must be something else with the mail process I don't understand.



via Chebli Mohamed

Laravel 5.2: Ajax login not working on live server, but working fine on localhost. Auth not working on live server

I am making a project in laravel 5.2 I have an issue.

this is a school management system where admin/teachers/students login to see their dashboard.

I have made a login page where username and email is given and users can login.

I have my own table for site users named "systemusers".

login is working fine on localhost but its not working on live server.

Auth is not working and users are redirected to login page again.



via Chebli Mohamed

Laravel Method store does not exist

I am trying to copy a file to my server Public Folder.

I am getting the following error :

BadMethodCallException in Macroable.php line 74: Method store does not exist.

This is the html to upload the file :

 <form action="/leads/csvFiles" method="post" enctype="multipart/form-data">
                            
                            <input type="file" name="csvfile" />
                            <input type="submit"/>
                        </form>

And here is the Route:

Route::post('leads/csvFiles', function(){

request()->file('csvfile')->store('Public');
return back();


});



via Chebli Mohamed

Laravel Model - All ID's return 1

I want to get all the projects through a group. I got that working now, but I can't seem to get the right ID's. I keep getting 1 as the ID for all my posts. Am I doing something wrong?

ProjectController.php

public function index()
{
    $projects = \Auth::user()->projects;
    dd($projects);
    return view('projects.home', compact('projects'));
}

User.php

public function projects()
{
    return $this->hasManyThrough(
        'App\Project', 'App\Group',
        'id', 'group_id', 'group_id'
    );
}

Dump (all items have the same attribute > id, all the other attributes are good)

Collection {#224 ▼
  #items: array:8 [▼
    0 => Project {#225 ▼
      #table: "projects"
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▼
        "id" => 1
        "name" => "project.com"
        "display_name" => "Project 1"
        "group_id" => 1
        "active" => 0
        "created_at" => null
        "updated_at" => "2017-03-29 12:21:47"
      ]
      #original: array:7 [▶]
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #events: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
    1 => Project {#226 ▶}



via Chebli Mohamed

How to insert array fields data in Laravel5

How can i insert multiple text fields data with laravel. I have two fields.

<input type="text" name="title[]" />
<input type="text" name="email[]" />

Now in controller i can get these values like this.

$name =  $request->title;
$description =  $request->email;

How can i add this with eloquent.



via Chebli Mohamed

Return Collection after update()?

Using Raw, how to return collection of updated row?

For example:

$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);

I was expecting dd($updated) to return updated row of collection but it returned 1.

 should return 123



via Chebli Mohamed

Add custom atrribute to json response

I have model something like that with custom attribute

class MyModel extends Model
{
    public function getExtraAttribute(){
        return 'some string'; //etc.
    }
}

And for controller method i have this

return MyModel::where('user_id', Auth::user()->id)->get();

But i don't see 'extra' attribute on json response

P.s. extra isn't column from database.



via Chebli Mohamed

withInput() doesn't work

And when I use it with withError(), it does not work either.

This works:

if ($validation->fails()) {
    //////////// Works and return the $errors array
    return redirect()->back()->withErrors($validation);                         
}

This doesn't work:

if ($validation->fails()) {
    return redirect()->back()->withInput();                         
}

This doesn't work too (either for withInput() and for withErrors())

if ($validation->fails()) {
    return redirect()->back()->withInput()->withErrors($validacion);
}

This is symptom of ... what problem?



via Chebli Mohamed

Returning javascript view in Laravel

In Ruby on Rails In my controller I can do something like this:

def jstest
    respond_to do |format|
        format.js
    end
end

This would return jstest.js.erb from the relevant views directory

jstest.js.erb

alert("Hello World")

The result being I get hello world alert.

I want to do the same thing in Laravel

In my controller I have:

public function jstest(  )
{
    return view('jstest');
}

in my view (which I have tried with both jstest.blade.js and just jstest.js)

but I get the error, view cannot be found.

The only way I get this to work is by calling the view jstest.blade.php and including my js in a <script> tag within this php file. but this feels a bit wrong...?

Is this even possible in Laravel? If so, where am I going wrong?



via Chebli Mohamed

How to get all month record count in laravel

I have applied group by with with created_at column using DB query but like to do it by laravel eloquent

Output should be like this:-

Array
(
  [1] => 2
  [2] => 3
  [3] => 7
  [4] => 4
  [5] => 5
  [6] => 7
  [7] => 2
  [8] => 9
  [9] => 0
  [10] => 4
  [11] => 0
  [12] => 0
)

Please provide any help me to do this.



via Chebli Mohamed

ViewComposer Doesn't Work

I have made a header.blade/php which is extended to many View pages. in header menu items come from database.So I used ViewComposer.

Here is my ComposerServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {

         View::composer(['cart.layouts.header'], 'App\Http\ViewComposers\CategoryComposer@compose');
    }

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

here is the CategoryComposer Class:

<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;

class CategoryComposer
{
    public $categoryList = [];
    /**
     * Create a movie composer.
     *
     * @return void
     */
    public function __construct()
    {
        $this->categoryList = \DB::table('categories')
                            ->select('categories.*')
                            ->get();
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('categories', end($this->categoryList));
    }
}

I have also registered the Service Provider in config/app

But the problem is I got error in other pages like Undefined variable: categories

Can you suggest me what could be the Error here?



via Chebli Mohamed