samedi 30 juin 2018

store foreign key as zero instead of it's value

I have a table that all the values are foreign keys ,when I store these values it save it as zero not the value that I chose ,

public function create()
{
    $type=type::query()->pluck('type');
    $color=color::query()->pluck('colore');
    $region=region::query()->pluck('country');
    $size=size::query()->pluck('size');
    $brand=brand::query()->pluck('company');
    //$price=new_product::query()->pluck('price');
    return view('sale',compact('type','color','region','size','brand'));
}

public function store(Request $request)
{

    new_product::create($request->all());
    return redirect()->route('sale.index');
}

the model:

class new_product extends Model
{
    protected $table = 'enter_new_product';
    protected $fillable = ['type_id', 'color_id', 'region_id', 'size_id', 'brand_id','price'];

    public function type()
    {
        return $this->hasMany(type::class);
    }

    public function size()
    {
        return $this->hasMany(size::class);
    }

    public function color()
    {
        return $this->hasMany(color::class);
    }

    public function region()
    {
        return $this->hasMany(region::class);
    }

    public function brand()
    {
        return $this->hasMany(brand::class);
    }
}



via Chebli Mohamed

Laravel 5.6 Trying to get property of non-object

When i try echo the value i receive an exeception. I check the collection with dd() and is not null.

My Models:

Cliente:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cliente extends Model
{
    protected $table = 'clientes';

    public function ordens() {
        return $this->hasMany('App\OrdemServico','cliente_id');
    }
}

OrdemServico:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OrdemServico extends Model
{
    protected $table = 'ordens_servico';

    public function clientes() {
        return $this->belongsTo('App\Cliente','id');
    }
}

OrdemServicoController:

public function index()
{

    $ordens = OrdemServico::with('clientes')->get();

    return view('home',compact('ordens'));

}

Part View Home:

             <table class="table">
                    <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Nome Cliente</th>
                        <th scope="col">Modelo</th>
                        <th scope="col">Status O.S</th>
                    </tr>
                    </thead>
                @foreach($ordens as $ordem)
                    <?php //dd($ordem->clientes->nome); ?>
                    <tr>
                        <th scope="row"></th>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td><button class="btn btn-outline-primary" onclick="location.href=''">Mostrar mais</button></td>
                    </tr>
                @endforeach

                    </tbody>
                </table>

When i

<?php dd($ordem->clientes->nome); ?>

I receive:

dd() return

But when i try echo the value, i receive a execpetion.

dd() of $ordem.

https://gist.github.com/vgoncalves13/8140a7a1bf2cb85fe4d16da20ea34acc



via Chebli Mohamed

Moving routes/web.php file gives class not found error

I'm working with the Laravel 5.6 framework and I want to move the routes file to another directory. I moved it to the ~/config/routes/web.php from the original ~/routes/web.php directory.

I then changed the mapWebRoutes method in my RouteServiceProvider to this:

Route::middleware('web')
     ->namespace($this->namespace)
     ->group(base_path('config/routes/web.php'));

Now when I try to start up laravel I get the error:

In web.php line 14: Class 'Route' not found

I already checked the aliases array in my app.php config file. There it's just the right class:

'Route'        => Illuminate\Support\Facades\Route::class,

When I change my routes directory back to the original ~/routes/web.php directory, every works.

I also tried to import the class into the web.php routes file like this:

use Illuminate\Support\Facades\Route;

Then I received this error when trying to start up laravel.

In Facade.php line 218: A facade root has not been set.

How can I make it so that I can move my routes file to another directory without getting this error?



via Chebli Mohamed

Form Intake & Mass assignment in Laravel

I'm developing a Laravel Web Application that involves storing lots of data in the database so far I've been using the regular Laravel Store as follows partially because I prefer this way & partially because I may need to use the Model Events in the future(Model Events don't fire in case of Mass Assignment):

$product = new Product;
$product->name = "EXT";
// MANY MORE FIELDS
$product->save();

But I've read somewhere that It's not a good practice to do it this way instead use the Mass assignment as that is faster & more efficient.

Is that correct? Should I keep using the method I'm using or should I switch to Mass Assignment/Update?

PS: I'm aware that the security risks from Mass Assignment can be averted by $gaurded & $fillable.



via Chebli Mohamed

Changing version of bootstrap from 4 to 3

In the latest installation of Laravel it comes with Boostrap 4. But I do not want to use Bootstrap 4. In my Laravel project I changed the package.json as follows:

"devDependencies": {
        "axios": "^0.18",
        "bootstrap-sass": "^3.3.7",
        "popper.js": "^1.12",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^2.0",
        "lodash": "^4.17.4",
        "vue": "^2.5.7"
}

And then I run "npm install". No when I run "npm run dev", i get lots of error like:

> @ development C:\LarProjects\larOne
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

 95% emitting

 ERROR  Failed to compile with 3 errors                                                                                             23:10:44
 error  in ./resources/assets/sass/app.scss

Module build failed:
undefined
^
      File to import not found or unreadable: ~bootstrap/scss/bootstrap.
      in C:\LarProjects\larOne\resources\assets\sass\app.scss (line 9, column 1)

 @ ./resources/assets/sass/app.scss 4:14-266
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

 error  in ./resources/assets/sass/app.scss

Module build failed: ModuleBuildError: Module build failed:
undefined
^
      File to import not found or unreadable: ~bootstrap/scss/bootstrap.
      in C:\LarProjects\larOne\resources\assets\sass\app.scss (line 9, column 1)
    at runLoaders (C:\LarProjects\larOne\node_modules\webpack\lib\NormalModule.js:195:19)
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:364:11
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:230:18
    at context.callback (C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
    at Object.asyncSassJobQueue.push [as callback] (C:\LarProjects\larOne\node_modules\sass-loader\lib\loader.js:55:13)
    at Object.done [as callback] (C:\LarProjects\larOne\node_modules\neo-async\async.js:7974:18)
    at options.error (C:\LarProjects\larOne\node_modules\node-sass\lib\index.js:294:32)

 error  in ./resources/assets/sass/app.scss

Module build failed: ModuleBuildError: Module build failed:
undefined
^
      File to import not found or unreadable: ~bootstrap/scss/bootstrap.
      in C:\LarProjects\larOne\resources\assets\sass\app.scss (line 9, column 1)
    at runLoaders (C:\LarProjects\larOne\node_modules\webpack\lib\NormalModule.js:195:19)
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:364:11
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:230:18
    at context.callback (C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
    at Object.asyncSassJobQueue.push [as callback] (C:\LarProjects\larOne\node_modules\sass-loader\lib\loader.js:55:13)
    at Object.done [as callback] (C:\LarProjects\larOne\node_modules\neo-async\async.js:7974:18)
    at options.error (C:\LarProjects\larOne\node_modules\node-sass\lib\index.js:294:32)
                                                                                                                                    Asset
  Size  Chunks                    Chunk Names
/js/app.js  1.25 MB       0  [emitted]  [big]  /js/app

WARNING in ./resources/assets/js/bootstrap.js
Module not found: Error: Can't resolve 'bootstrap' in 'C:\LarProjects\larOne\resources\assets\js'
 @ ./resources/assets/js/bootstrap.js 14:2-22
 @ ./resources/assets/js/app.js
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

ERROR in ./node_modules/css-loader??ref--5-2!./node_modules/postcss-loader/lib??postcss!./node_modules/resolve-url-loader??ref--5-4!./node_modules/sass-loader/lib/loader.js??ref--5-5!./resources/assets/sass/app.scss
Module build failed:
undefined
^
      File to import not found or unreadable: ~bootstrap/scss/bootstrap.
      in C:\LarProjects\larOne\resources\assets\sass\app.scss (line 9, column 1)
 @ ./resources/assets/sass/app.scss 4:14-266
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

ERROR in ./resources/assets/sass/app.scss
Module build failed: ModuleBuildError: Module build failed:
undefined
^
      File to import not found or unreadable: ~bootstrap/scss/bootstrap.
      in C:\LarProjects\larOne\resources\assets\sass\app.scss (line 9, column 1)
    at runLoaders (C:\LarProjects\larOne\node_modules\webpack\lib\NormalModule.js:195:19)
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:364:11
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:230:18
    at context.callback (C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
    at Object.asyncSassJobQueue.push [as callback] (C:\LarProjects\larOne\node_modules\sass-loader\lib\loader.js:55:13)
    at Object.done [as callback] (C:\LarProjects\larOne\node_modules\neo-async\async.js:7974:18)
    at options.error (C:\LarProjects\larOne\node_modules\node-sass\lib\index.js:294:32)
 @ ./resources/assets/sass/app.scss
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

ERROR in ./resources/assets/sass/app.scss
Module build failed: ModuleBuildError: Module build failed:
undefined
^
      File to import not found or unreadable: ~bootstrap/scss/bootstrap.
      in C:\LarProjects\larOne\resources\assets\sass\app.scss (line 9, column 1)
    at runLoaders (C:\LarProjects\larOne\node_modules\webpack\lib\NormalModule.js:195:19)
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:364:11
    at C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:230:18
    at context.callback (C:\LarProjects\larOne\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
    at Object.asyncSassJobQueue.push [as callback] (C:\LarProjects\larOne\node_modules\sass-loader\lib\loader.js:55:13)
    at Object.done [as callback] (C:\LarProjects\larOne\node_modules\neo-async\async.js:7974:18)
    at options.error (C:\LarProjects\larOne\node_modules\node-sass\lib\index.js:294:32)
 @ ./resources/assets/sass/app.scss
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hp\AppData\Roaming\npm-cache\_logs\2018-06-30T20_10_44_115Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hp\AppData\Roaming\npm-cache\_logs\2018-06-30T20_10_44_144Z-debug.log

I thought that this may be wrong way that i am doing. I actually think that we should have a way to select the version of bootstrap while creating laravel project with composer.



via Chebli Mohamed

Laravel, trying to use helper to display PDF

I'm trying to display a PDF file I have in my storage\reports folder inline in the browser.

My file is: storage\reports\Real_Estate_Test.pdf

I have a helper file: app\Helpers\helpers.php

I call the PDF from my blade with:

where

$filepath = storage_path().'\reports';
$ext = "pdf";
$filename = "Real_Estate_Test";

In my helper file I have:

<?php

use Response;

if (! function_exists('viewReport')) 
{
    function viewReport($filepath, $ext, $filename)
    {
$filename.".".$ext, [], 'inline');

        $headers = [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; ' . $filepath."\\".$filename.".".$ext,
        ];

        return Response::make(File::get($filepath."\\".$filename.".".$ext), 200, $headers);

    }
}

In my composer.json I have:

 "autoload": {
    "classmap": [
      "database"
    ],
    "psr-4": {
      "App\\": "app/"
    },
    "files": [
      "app/Helpers/helpers.php"
    ]
  },

I get this error at the top of my page:

Warning: The use statement with non-compound name 'Response' has no effect in C:\xampp\htdocs\DS_dev_01\app\Helpers\helpers.php on line 4

where line 4 is use Response;

If I comment out line 4 I then get nothing.

I've also tried doing this with this suggestion from another post:

return response()->download($filepath."\\".$filename.".".$ext, $filename.".".$ext, [], 'inline');

and I get the following string displayed at the top of my page (no PDF):

HTTP/1.0 200 OK Cache-Control: public Content-Disposition: inline; filename="Real_Estate_Test.pdf" Date: Sat, 30 Jun 2018 18:21:48 GMT Last-Modified: Sat, 30 Jun 2018 18:21:48 GMT

which looks really close to a command to load and display my PDF.

Any suggestions as to what I'm doing wrong. Trying to piece together hints from Laravel docs and many posts is not getting me anywhere.

I'm running Laravel 5.5 on XAMPP in Win10 with PHP7

Thanks in advance



via Chebli Mohamed

Python script execution error in Laravel controller

Currently my scripts work perfectly within the schedule that run at specific times within my server's cron.Currently my scripts work perfectly within the schedule that run at specific times within my server's cron.

The problem is occurring when I try to execute the method inside the controller, this method basically uses a shell_exec() that executes a script in python and this return is what I deal with Laravel.

When I call it from the console or the schedule it works correctly, but when I call the method or even an \Artisan::call('schedule:test'); it returns the same error saying that it is not finding the geckdriver.

The command "python C:/wamp64/www/MoneyGuard/pythonGuard/tesouro_direto/tesouro_direto_precos_taxa_titulo.py" failed.
Exit Code: 1(General error)
Working directory: C:\wamp64\www\MoneyGuard\public
Output:
================
[ {"inicio": "2018-06-30 11:04:23.830834"},
Error Output:
================
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)
  File "C:\Program Files (x86)\Python36-32\lib\subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "C:\Program Files (x86)\Python36-32\lib\subprocess.py", line 997, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] O sistema não pode encontrar o arquivo especificado
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:/wamp64/www/MoneyGuard/pythonGuard/tesouro_direto/tesouro_direto_precos_taxa_titulo.py", line 17, in <module>
    firefox = webdriver.Firefox(firefox_options=opts)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 152, in __init__
    self.service.start()
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 83, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. 

When I run it inside the terminal: it works perfectly:

λ php artisan schedule:teste
[ {"inicio": "2018-06-29 17:23:08.963534"},
 { "titulo": "Tesouro IPCA+ 2024", "vencimento": "2024-08-15 00:00:00", "taxa_rendimento": "5.62", "valor_minimo": "44.50", "preco_unitario": "2225.41" },
 { "titulo": "Tesouro IPCA+ 2035", "vencimento": "2035-05-15 00:00:00", "taxa_rendimento": "5.87", "valor_minimo": "35.72", "preco_unitario": "1190.74" },
 { "titulo": "Tesouro IPCA+ 2045", "vencimento": "2045-05-15 00:00:00", "taxa_rendimento": "5.87", "valor_minimo": "33.70", "preco_unitario": "674.18" },
 { "titulo": "Tesouro IPCA+ com Juros Semestrais 2026", "vencimento": "2026-08-15 00:00:00", "taxa_rendimento": "5.68", "valor_minimo": "32.40", "preco_unitario": "3240.59" },
 { "titulo": "Tesouro IPCA+ com Juros Semestrais 2035", "vencimento": "2035-05-15 00:00:00", "taxa_rendimento": "5.79", "valor_minimo": "32.04", "preco_unitario": "3204.72" },
 { "titulo": "Tesouro IPCA+ com Juros Semestrais 2050", "vencimento": "2050-08-15 00:00:00", "taxa_rendimento": "5.88", "valor_minimo": "32.36", "preco_unitario": "3236.30" },
 { "titulo": "Tesouro Prefixado 2021", "vencimento": "2021-01-01 00:00:00", "taxa_rendimento": "9.20", "valor_minimo": "32.09", "preco_unitario": "802.49" },
 { "titulo": "Tesouro Prefixado 2025", "vencimento": "2025-01-01 00:00:00", "taxa_rendimento": "11.44", "valor_minimo": "34.66", "preco_unitario": "495.21" },
 { "titulo": "Tesouro Selic 2023", "vencimento": "2023-03-01 00:00:00", "taxa_rendimento": "0.02", "valor_minimo": "95.72", "preco_unitario": "9572.17" },
{"fim": "2018-06-29 17:23:19.484442"} ]

Python Script: tesouro_direto_precos_taxa_titulo.py

From what I'm noticing when I run the command inside the controller, it is not using the path of my system. the question is why?

I thank you in advance for any help.



via Chebli Mohamed

Class 'Importer' not found patosmack/laravel-excel - laravel-5

Actually I want to import an excel file to database using patosmack/laravel-excel library. I Followed all these steps given in this link but in the end I got this error. I don't know how to fix it. I searched this error every where no answer found.

enter image description here



via Chebli Mohamed

Uploading data from excel to MySQL DB with Laravel and Maatwebsite\Excel

I am working on a application, in which the users can extract data from excel file to MySQL DB. The application will check every row of ID collunm from excel file with content_id table of the database. If any ID matches any record of DB, then the row will update. Otherwise it will create a new record in DB. This is the code of my function in controller:

public function upload(Request $request)
{

    if($request->hasFile('excel')){
        Excel::load($request->file('excel')->getRealPath(), function ($reader) {
            foreach ($reader->toArray() as $key => $row) {
                foreach ($row as $record => $info){
                    if ($content = Content::find($info['id'])) {
                        $content->views()->save($info['views']);
                    }
                    else{
                        $content = new Content();
                        $content->title = $info['title'];
                        $content->content_id = $info['id'];
                        //$content->views()->save($info['views']);
                        $content->save();
                    }
                }
            }
        });
    }


    return redirect()->back();

}

But it shows error as like below: enter image description here

I have tried to find the error by using dd() and print_r(). But cannot find what is the problem. Along with this, I am also confused about the quality of my code as I am using foreach loop in another foreach loop. So, does anyone have any solution? Thanks in advance. I am using Maatwebsite\Excel to handle excel import/export etc.



via Chebli Mohamed

Using callable params to modify a query

I am using https://github.com/BRACKETS-by-TRIAD/craftable to generate an admin panel for my app.

I have an Organisation model that belongs to an Organisation Type model.

In the index listing, I want to be able to display the Organisation Type name rather than the _id. To do this, I have to modify this query, to eager load the relationship using the 'with' method.

The method signature for the listing is:

public static function processRequestAndGet($request, $columns = array(), $searchIn = null, $modifyQuery = null, $locale = null)

and the index method is:

$data = AdminListing::create(Organisation::class)->processRequestAndGet(
        // pass the request with params
            $request,

            // set columns to query
            ['id', 'organisation_type_id', 'name', 'active'],

            // set columns to searchIn
            ['id', 'name']
        );

        if ($request->ajax()) {
            return ['data' => $data];
        }

        return view('admin.organisation.index', ['data' => $data]);

Can someone help with this, please?



via Chebli Mohamed

Laravel - Fullcalendar time issue

I have implemented fullcalendar in my laravel application. This is my Database, I have the parameters in DateTime format but still it shows events in full day instead of time specified: Month View Day View.

here is my code

public function create()
{
    $events = Booking::get();
    $event_list = [];
    foreach ($events as $key => $event) {

        $event_list[] = Calendar::event(
            // $event->resouces_id,
            "Event Name",
            true,
            new \DateTime($event->bk_date),
            new \DateTime($event->end_date.'+1 day')
        );            
    }

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


    $resources = resources::all();

    return view('Staff.Booking',compact('resources','calender_details'));
}

Where i am going wrong?



via Chebli Mohamed

vendredi 29 juin 2018

Multilevel relationship whereHas on eloquent Model in Laravel

I'd like to find Project::with('tasks.tags')->find(2);

where only tasks with a particular id of tag return in the result set for a particular project.

For ex. I'd like to find a project with ID of 2 with all its tasks and tasks with tags with only id of 1.

I have tried various ways but have failed so far.

I have tried:

$project = Project::with('tasks.tags')->whereHas('tasks', function($query){
            $query->whereHas('tags', function($query) {
                $query->where('id', 1);
            });
})->find(1);

And:

$project = Project::with('tasks.tags')->whereHas('tasks', function($query){
            $query->whereHas('tags', function($query) {
                $query->where('tag_id', 1);
            });
})->find(1);

This is how the relationships are setup:

In Project.php

public function tasks()
{
    return $this->hasMany(Task::class, 'project_id')->setEagerLoads([]);
}

In Task.php

public function tags()
{
        return $this->morphToMany(Tag::class, 'taggable')->setEagerLoads([]);

}

Note that relationship between Task and Tags is of morphToMany.

Any pointers?



via Chebli Mohamed

How to add botman 2.0 to existing laravel 5.6 project?

I have an existing laravel project. I tried installing botman using "composer require botman/botman" but there are errors preventing me from adding botman:

Problem 1
   - Conclusion: don't install botman/botman 2.3.3
   - Conclusion: don't install botman/botman 2.3.2
   - Conclusion: don't install botman/botman 2.3.1
   - Conclusion: remove symfony/http-foundation v4.1.1

and more lines.

I also tried "composer require botman/studio-addons" but it only use version 1.2 of botman.



via Chebli Mohamed

Get relationship based on field value

I have a Model NewsCategory that contains 2 relationship (it may contain more in the future) NewsCategory model belongs to a News model, and the idea is to apply a filter to the News based in the category that the user selected or just fetch "all" the news, the problem is that the NewsCategory relationships belongs to different tables that each have its own purpose.

So in my NewsCategory model i want to access the relationship using the field table_id and a type that tells me if it is a headquarter or a program, so my model is

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class NewsCategory extends Model
{
    //
    public function headquarters()
    {
        return $this->belongsTo('App\Models\Headquarter','table_id');
    }
    public function programs()
    {
        return $this->belongsTo('App\Models\Program','table_id');
    }
}

The problem comes when i do not filter by the relationship and i want to get something like this.

$noticia = Noticia::with('titles')
->with('descriptions')
->with('images')
->with(['categories' => function($categories){
    //i want to get the relationship based on the type of the NewsCategory
    //so when printing i can tell wich category it belongs based it the relationship exists
    switch($categories->type){
        case 'headquarter':
            $categories->with('headquarters');
            break;
        case 'program':
            $categories->with('programs');
            break;
        ....
    }
}])
->get();

But this give an error where Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$type

So how could i make this happends? i have tried putting the type in the News model insted of the NewsCategory but i dont know how to access the parent field inside the relationship function.



via Chebli Mohamed

Deploy Laravel App

I'm trying to deploy my Laravel app and block the access to the others files like .env I put all my laravel app in the www folder, and I add this htaccess :

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule> 

But when I go to my domain url I have all the files.. seem like my htaccess is not working (he's on the Laravel app root)

This is what I get when I go to my website url (this is the www foolder)



via Chebli Mohamed

Laravel Multi Select with DB Array

Guide me the right way to do a multi select Vales in form Edit.

I am storing the values of size like this in serialize array.

 @foreach($sizes as $size)
   <option value=""></option>
 @endforeach

Now in edit i want to show the selected values with this sizes also, i tired in array + ternary operator but failed to do it here is what i am trying

@foreach($sizes as $size)

<option value=" "></option>

@endforeach



via Chebli Mohamed

Only run commands in deploy script when specific files have been changed

I just started running npm install and npm run production through my Laravel Forge deploy script to compile my assets on the production site. However I noticed that running npm install slows down my deployment by a couple minutes, and I don't think it should need to be run every time I need to push up an update.

Here's my current deploy script:

cd /home/forge/website.com
git pull origin master
npm install
npm run production # Run build process
composer install --no-interaction --prefer-dist --optimize-autoloader
echo "" | sudo -S service php7.2-fpm reload
if [ -f artisan ]
then
    php artisan route:clear
    php artisan route:cache
    php artisan migrate --force
    php artisan cache:clear
    php artisan config:clear
    php artisan config:cache
    php artisan horizon:terminate
fi

Is there a way to check if the package.json file has been changed before running npm install?

Here's something I've tried, but breaks the deploy script and I'm having trouble figuring out why it doesn't work.

cd /home/forge/website.com
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
check_run() {
    echo "$changed_files" | grep --quiet "$1" && eval "$2"
}
git pull origin master
check_run package.json "npm install"
npm run production # Run build process
composer install --no-interaction --prefer-dist --optimize-autoloader
echo "" | sudo -S service php7.2-fpm reload
if [ -f artisan ]
then
    php artisan route:clear
    php artisan route:cache
    php artisan migrate --force
    php artisan cache:clear
    php artisan config:clear
    php artisan config:cache
    php artisan horizon:terminate
fi



via Chebli Mohamed

Laravel: Defining rules or schema for a json field/column

I have a column in my database which it's json type: values.
But I need to enforce a schema.

  • It must be an array
  • Every object must have 2 and only 2 properties (required). code_name, and description
  • code_name must be unique inside that JSON array

Does Laravel has some out of the box feature for this? or do I need to manually decode the json on create and on update to validate that rules?

Till now. I only have this validation rules in my Model:

/**
 * The model validation rules.
 *
 * @var array
 */
public static $rules = [
    'values' => 'required|json', // TO BE CHECKED (values validation (json schema) and setter)
];

But that's not enough.

Important: this is not a duplicate question to: Laravel: validate json object



via Chebli Mohamed

Laravel: One to Many Poly relation not updating automatically

3 types of posts: Personal, Business & Nature.

Below is the Post Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;

Relation::morphMap([
          'Personal' => 'App\Personal',
          'Business' => 'App\Business',
          'Nature' => 'App\Nature',
        ]);

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

Below is the Personal Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;    

class Personal extends Model
{
    public function posts()
    {
        return $this->morphMany(Post::class,'postable');
    }
}

Likewise Busines & Nature models.

When I manually enter the data in phpMyAdmin, the tinker shows the result as required, but when I create a post from front-end (via form), the posts table remains unchanged.

I tried googling, but nothing works! :(



via Chebli Mohamed

Eloquent - access parent value in nested function

I'm trying to access the parent value, the posts date, in a nested function.

In my application, a user has many posts, with each post being associated to a product (textbook). Each time someone views a page with the product, a new row is added to the product-views table.

I want to return the cumulative amount of times the users products have been seen. I've been able to get all the users posts, then the associated product, and then the count of all the views of that product within the last year, at the location-viewed or, if no location was set, then anywhere.

Now I'd like to add another where() condition to only return views that have occured after the post was created. To do so, I need to get the posts date, e.g. views->product->post, while constructing the query like user->posts->product->views.

    // getting all of the users available posts
    $user = $request->user()->posts()->available()->with([
        // with the textbook (product) associated with the post
        'textbook' => function ($q) {
            // get the count of textbook-page views
            return $q->withCount([
                // from the related table views
                'views' => function ($q) {
                    // limit results to 'in the past month'
                    $q->whereRaw('`date-viewed` >= DATE_SUB(NOW(),INTERVAL 1 MONTH)')

                    // ===!!! now what? !!!=== How do I access the posts (parent (grandparent?)) date, so that I only select the rows that have been viewed after the post was created  ===!!!===
                    ->where('date-viewed', '>=', 'posts.date');
                },
            ]);
            //some cleanup
        }])->distinct()->get()->unique('isbn')->pluck('textbook.views_count')->sum();

How do I go backwards in a nested function to access the posts date?



via Chebli Mohamed

Laravel Dynamic Input Validation

I'm developing an application, where I'm creating dynamic input. Validation is working properly except one use case.

Validation rule is here:

return [ '*.id' => 'nullable|numeric', '*.name' => 'required|min:3|regex:/^[a-zA-Z0-9\s]+$/|unique:products,name,*.id,id,category_id,'.$this->route('id'), '*.quantity_available' => 'nullable|numeric|min:0', '*.quantity_sold' => 'nullable|numeric|min:0', '*.price'=> 'required|numeric|min:10', '*.sale_price' => 'required|numeric|min:10', ];

Please have a look over the following sent data:

{id: 5, category_id: 3, name: "Test 1", description: null, quantity_available: null, quantity_sold: null, price:40, sale_price:35}, {id: 6, category_id: 3, name: "Test 2", description: null, quantity_available: null, quantity_sold: null,price:40, sale_price:35}, {id: "", name: "Test 3", quantity_available: "", quantity_sold: "", price: 40, sale_price: 35}

Query: I want the product name to be unique as per the category_id and if a input has id present, then that product id would be ignored while product name unique validation.



via Chebli Mohamed

Is it possible to run a join on a variable created by a sub-query?

Right now I am running a sub-query to get the most recent status for a server, this sub-query is returning through the variable last_status.

 //This is ran when WithLastStatusDate() is called
$query->addSubSelect('last_status', ServerStatus::select('status_id')
    ->whereRaw('server_id = servers.id')
    ->latest()
);

$servers = Server::WithLastStatusDate()
    ->OrderBy('servers.id', 'desc')
    ->where('servers.isPublic', '=', 1)
    ->get(); 

What I am trying to do now is do a join on this so that it gives me the actual name of the status based on the result of this query in the statuses table. I have tried to do a simple left join but am getting the error that the last_status column isn't found.

$servers = Server::WithLastStatusDate()
    ->OrderBy('servers.id', 'desc')
    ->where('servers.isPublic', '=', 1)
    ->leftjoin('statuses','servers.last_status', '=', 'statuses.id')
    ->get(); 

Can anyone point me in the right direction on how to accomplish this?



via Chebli Mohamed

Create video thumbnail in laravel 5.5

I am working in a project in laravel and I want to create thumbnail when upload video

I am following this artical

https://packagist.org/packages/pawlox/video-thumbnail

pawlox/video-thumbnail

when I call this

 $thumb = VideoThumbnail::createThumbnail(asset('public/stories/videos/21530251287.mp4'), asset("public/images/"), 'thumb.jpg', 2, 600, 600);

its return

Pawlox\VideoThumbnail\VideoThumbnail Object(
[FFMpeg:protected] => 
[videoObject:protected] => 
[videoURL:protected] => http://localhost/sunbay/yms/public/stories/2/videos/21530251287.mp4
[storageURL:protected] => http://localhost/sunbay/yms/public/images
[thumbName:protected] => thumb.jpg
[fullFile:protected] => http://localhost/sunbay/yms/public/images/thumb.jpg
[height:protected] => 600
[width:protected] => 600
[screenShotTime:protected] => 2 )

but thumb not generated.

Please let me know what wrong I am doing. and how to resolved it.

Thanks in advance.



via Chebli Mohamed

Is it better to post json data or just key-value pairs in Laravel Apis?

i have developed the Api in Laravel now one of my team member saying that i will post the data in Json format during api call. now what should i do?

is it better to post data in Json format or just use key-value pairs? please help



via Chebli Mohamed

Laravel creating multiple entries same time

When some users trying to hit the signup button they are getting integrity constrain error,

$user = User::where("username", $username)->first(); if(is_null($user)){ $user = new User; } ...

This code is not actually validating because, i am getting a simultaneous request, so both the requests are trying to create the user with same username. when i removed the unique constrain for testing, i found duplicated users. I have added a button disable functionality on submit but the issue still exists.

So in short

  1. Users trying to signup
  2. In controller I am getting 2 requests same time , both request are trying to create the same user.

is there any way I can handle the issue ?



via Chebli Mohamed

Remove time() string from filenames in Laravel when showing

I am using time() function to add time string to the file names like this and storing them in the database

$filename = time() . $file->getClientOriginalName();

But How Can I remove this string when I show the files to the user and when the user downloads the file. I am using Laravel by the way.



via Chebli Mohamed

Bulk update in Laravel

I have a string with multiple update queries, example:

$string = "UPDATE `student` SET `isams_id`=0001,`name`='stu name',`registration_id`='258911',`classid`=2,`section`='A',`house_name`='ELM',`status`=1,`updated_at`='2018-06-29 06:49:15' WHERE `registration_id`='258911'; UPDATE `student` SET `isams_id`=0002,`name`='xxx,`registration_id`='258912',`classid`=3,`section`='A',`house_name`='sss',`status`=1,`updated_at`='2018-06-29 06:49:15' WHERE `registration_id`='258912';"

Like this, I have around 2500 update queries in my string. For bulk update I am using DB::select( DB::raw($string));. But this returns error like,

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE `student` SET `isams_id`=0002,`name`='xxx',`registration_i' at line 1

How to resolve this. Please help me.



via Chebli Mohamed

Laravel: Sending Mail with Queue ignores Locale

My Email template looks like this:

@component('mail::message')
# 

@lang('welcome.message')

This

\App::setLocale('de);

$activeMail =  new \App\Mail\Register\Activate($user);

\Mail::to($user)->send($activeMail);

will send an mail with German text.

However, when I use a queue

\App::setLocale('de);

$activeMail =  new \App\Mail\Register\Activate($user);

\Mail::to($user)->queue($activeMail);

The mail is send in English, which is the default language of my app. How can I send a message in German with the queue without changing the default language?



via Chebli Mohamed

Custom request headers cause CORS

In my project, my custom header cause CORS and when I remove it from request headers, everything works truly.

Laravel is my back-end and I send requests with axios.

Here is my middleware to add CORS headers to response,

 public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Credentials', 'true');
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PATCH, PUT, DELETE');
        $response->header('Access-Control-Allow-Headers', 'Auth-Type, X-API-KEY, Origin, Content-Type, Accept, Authorization');

        return $response;
    }

Auth-Type is my custom header and my front-end request is like,

function getCities(data) {
    return axios({
        method: 'get',
        url: appConstants.BASE_URL + '/city/query',
        headers: {
            'Content-Type': 'application/json',
            'Auth-Type': 'admin'
        },
        params: data
    });
}

When I send the request containing Auth-Type, Chrome log me an error like:

Failed to load http://example.com/api/v1/city/query: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.

As you seen in my CORS middleware, I added Auth-Type as my allowed headers in Access-Control-Allow-Headers. Also in this situation (I mean custom headers passing), the get method converts to OPTIONS.

Any solutions will appreciate.



via Chebli Mohamed

Laravel Passport - which grant to use for my users apps?

I have application where users can register and add their own applications (websites, mobile applications).

For each of these applications, I want to give access to my API and allow to get products form my database.

For example: User X signup in my app, adds his blog user-X-blog.com and get access token. Next he can call to my API and get some products to show on his blog post.

Which grant should I implement to make my API based on Laravel Passport safe and useful (each user application with its own token, no user login required to make api call, long-lived tokens)?

Is it good idea to create for each user apps dedicated client and use client credentials grant? It doesn't look very safe for me (or maybe I'm wrong).



via Chebli Mohamed

How to inherit connection using Laravel 5.6

i have 3 Adressen db's they all have excat same structure. I'm changing the connection with the static method on(....) when the variable $mandant changes. This is working but now i need to eager load several different relationships in a single operation. Is it possible to inherit the connection from the parent ?

this is my controller:

class DatasheetController extends Controller
{

    public function getMandant($mandant)
    {
        ....
    }

    public function show($mandant, $adresse)
    {

        $address = Adressen::on($this->getMandant($mandant))->find($adresse);

        dd($address->with('Kontokorrent')->get());

        return view('addresses.show', compact('address'));

    }

}

here my relationship:

class Adressen extends Model
{

    protected $primaryKey = 'Adresse';
    protected $table = 'Adressen';
    public $incrementing = false;
    public $timestamps = false;

    public function kontokorrent()
    {

        return $this->hasOne(Kontokorrent::class, 'Adresse');

    }

}

--

class Kontokorrent extends Model
{

    protected $primaryKey = 'Adresse';
    protected $table = 'Kontokorrent';
    public $incrementing = false;
    public $timestamps = false;


    public function address()
    {

         return $this->belongsTo(Adressen::class, 'Adresse');

    }

}



via Chebli Mohamed

Run command get error in AppServiceProvider

I run command and get error "Call to a member function getAction() on null" in AppServiceProvider.
If i comment it, command run ok. My AppServiceProvider.php :

app('view')->composer(['layouts.admin-app', 'admin.*'], function ($view) {
            $action = app('request')->route()->getAction();

            $controller = class_basename($action['controller']);

            list($controller, $action) = explode('@', $controller);
            $controller = str_replace('controller', '', strtolower($controller));

            $view->with(compact('controller', 'action'));
        });

I researched many hours but still not able to solve it.



via Chebli Mohamed

How to set vue component when root of site is opened

In my laravel 5.6/vue.js 2.5.7 / vuetify": "^1.0.8" I need to set vue component when root of site is opened I mean when I run url

http://local-artists-rating.com

see url reopened

http://local-artists-rating.com/#/

It has navbar, footer defined in my pages, but not any content I defined in resources/assets/js/components/appRoot.vue.

In my resources/assets/js/app.js:

require('./bootstrap');

window.Vue = require('vue');

import Vue from 'vue'

import VueRouter from 'vue-router';
window.Vue.use(VueRouter);

...
import AppRoot from './components/appRoot.vue';
...

const routes = [
{
    path: '/',
    components: {
        ...
        appRoot: AppRoot,
        ...

    }
    ...

    {path: '/not-found/:invalid_url?', component: NotFound, name: 'notFound'},
    {path: '/login', component: AppLogin, name: 'appLogin'},
    {path: '/', component: AppRoot, name: 'appRoot'},
}
    ...

const router = new VueRouter( {
    mode: 'hash', // default
    routes
})


router.beforeEach((to, from, next) => {
    if (!to.matched.length) {
        next(  '/not-found/'+encodeURIComponent(to.path)  );
    } else {
        next();
    }
})



...

new Vue({ router, i18n,

    data:{
        app_title: '',
    },

    mixins : [appMixin],

    created() {
    }, // created() {

    mounted() {

    }, // mounted(){


} ).$mount('#app')  // new Vue({ router,

If I commented line :

path: '/',
at top of routes definitions, I got error in console:

app.js?dt=1529909735:73635 Uncaught Error: [vue-router] "path" is required in a route configuration.
    at assert (app.js?dt=1529909735:73635)
    at addRouteRecord (app.js?dt=1529909735:74771)
    at app.js?dt=1529909735:74741
    at Array.forEach (<anonymous>)
    at createRouteMap (app.js?dt=1529909735:74740)
    at createMatcher (app.js?dt=1529909735:74961)
    at new VueRouter (app.js?dt=1529909735:76055)
    at Object._typeof (app.js?dt=1529909735:4945)
    at __webpack_require__ (app.js?dt=1529909735:20)
    at Object.<anonymous> (app.js?dt=1529909735:50854)

In my resources/views/layouts/app.blade.php:

<!DOCTYPE html>
<html lang="">
<head>
    <?php $current_template= 'artists_rating_light' ?>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Cache-Control" content="no-cache">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="">

    <title id="app_title"></title>


    <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.css">
    <link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">

</head>

<body>

<div id="app">

    <backend-app-layout></backend-app-layout>

</div>

    @include('layouts.footer')
    <script src="?dt="></script>

</body>

</html>

Which is the right way ?

Thanks!



via Chebli Mohamed

jeudi 28 juin 2018

How to debug javascript (from the browser console) in Laravel?

In Laravel, your javascript resides in:
resources
    -assets
        -js
          -app.js

then you usually run "$ npm run watch" (if your still developing) and then the code gets "compiled" in:
public
   -js
    -app.js

But when you check your browser console the lines in red does not match the actual app.js located in your resource->assets->js folder.

Any suggestions to accurately debug javascript files in laravel?



via Chebli Mohamed

Laravel Passport Auth Stuck when run on standalone project for password based token authentication

Laravel Passport Auth Stuck when run on self server and client in same project for password based token authentication

LoginController

public function authenticaterrr(Request $request)

{
     $http = new Client();

    try{
                //dd("Hello");

        $response = $http->post(url('oauth/token'), [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => '2',
            'client_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            // 'username' => $request->get('username'),
            // 'password' => $request->get('password'),
              'username' => 'xxxxxx@xxxxx.com',
                'password' => 'xxxxx',
            'scope'     => '*',
         ],
         ]);

       //  $apiResponse = json_decode((string) $response->getBody(), true);

       // dd($apiResponse);
         $apiResponse = json_decode((string) $response->getBody(), true);

        dd($apiResponse);
        session(['api'=> $apiResponse]);
        session(['api-token'=> $apiResponse['access_token']]);
        return json_decode($response->getBody(), true);
    }catch (ClientException $exception){
        dd("Hello");
        return json_decode($exception->getResponse()->getBody(), true);
    }
}

IN Web.php

Route::get('/auth/api/validate', 'Auth\LoginController@authenticaterrr');

In PostMan It didn't Get and Stuck Here is Output

If i will create new Project and Use that than it will work for me so what would be solution to run in same project



via Chebli Mohamed

Vue JS Chat App UI

Good day everyone! I am developing a Chat App using Laravel + Laravel Echo + Pusher and Vue JS all the functionality are fine but I have a problem with the UI.

If you have a new chat, your message will display on the right side and if someone sends a chat on the chatbox, his/her message will display to the left.

I already made the UI

<div class="chat-log-container" id="chatlog">
    <div class="chat-log-content">
        <div v-if="currentSender === meSender">
            <ul id="mesender" class="me-sender" v-for="message in chats">
                <li>
                    <div class="sender-name" >  10:12 AM, Today</div>
                    <div class="sender-message wordwrap"></div>
                </li>
            </ul>
        </div>

        <div v-else>
            <ul class="other-sender" v-for="message in chats">
                <li>
                    <div class="sender-name" >  10:12 AM, Today</div>
                    <div class="sender-message wordwrap"></div>
                </li>
            </ul>
        </div>
    </div>
</div>

whenever I make a message, all messages will display on the right, if someone sends a chat, all messages will display on the left.

Thanks!



via Chebli Mohamed

Ajax Query not working with range sliders in Laravel

I am trying to get value from range slider and update my database using ajax but it is giving me 404 status error. I am using Laravel.

This is my route

Route::post('developer/work-progress/changeProgess','DeveloperController@changeProgess');

here is the html code

<div class="form-group row themered">
                    <label for="range_02" class="col-sm-2 col-xs-12 control-label"><b>Back-End</b><span class=" font-13 d-block text-muted clearfix">Set backend progress</span></label>
                    <div class="col-sm-10 col-xs-12">
                        <input type="text" id="range_01" name="frontend_percent">
                    </div>
                </div>

                <div class="form-group row themered">
                    <label for="range_02" class="col-sm-2 col-xs-12 control-label"><b>Front-End</b><span class=" font-13 d-block text-muted clearfix">Set frontend progress</span></label>
                    <div class="col-sm-10 col-xs-12">
                        <input type="text" id="range_02" name="backend_percent">
                    </div>
                </div>

                <div class="form-group">
                    <input class="progressId" type="hidden" name="id" value="">
                </div>

                <div>

                    <button class="btn btn-info changeProgress">Change</button>

                </div>

Here is my jquery code

  var frontend  = $('#range_01').val();
    var backend  = $('#range_02').val();

    $('#range_01').change(function () {
         frontend = $(this).val();
    });

    $('#range_02').change(function () {
        backend = $(this).val();

    });

    $('.changeProgress').click(function () {

        $.ajax({

            type: 'post',
            url: 'work-progress/changeProgress',
            dataType: 'json',

            data: {

                'frontend_percent' : frontend,
                'backend_percent' : backend,
                'id':   $('.progressId').val(),

            },

            headers: {"X-CSRF-Token": token},

            success : function (data) {
                console.log("worked");
            }

        });

    });

and this is the controller function

public function changeProgess(Request $request) {

    $data = Order::findOrFail($request->id);

    $data->frontend_percent = $request->frontend_percent;
    $data->backend_percent =  $request->frontend_percent;

    $data->save();

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

}

I can see my data in network tab when I inspect as well as the csrf-token. So I don't know where the problem is.



via Chebli Mohamed

How to clear url search laravel?

  1. Search.blade.php

        <form action="" method="get" id="main_search" >
             <input type="text" name="search" id="search" placeholder=" Search Movies">
             <button type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
        </form>
    
    
  2. Route

     Route::get('search', ['as' => 'getSearch', 'uses' => 'SearchController@getSearch']);
    
    

When doing the search the url results will be as follows

     http://www.example.com/search?search=keyword

how to convert url to

     http://www.example.com/search/keyword



via Chebli Mohamed

Laravel Common Services Through Inheritance

Question.

I have a bunch of controllers that are using a certain set of services. I was wondering if it is possible / right to utilize inheritance to save me from having to inject them into controllers all the time. This is what I was planning on doing.

class MasterController extends controller{
    public function _construct(){
            $this->userData = App::make(UserService::class)
            $this->fooData = App::make(FooService::class)
    }
}

class UserController extends MasterController {
    public function __construct(BashService $bashService){
        parent::__construct();
        $this->bashData = $bashService;
    }

    public function someFunction(){
        $something = $this->userData->doUserSomething();
    }
}

Is this a good idea to do? A really bad idea to do? Why or why not? I thought this might save me from having to inject common services again and again into controllers.

Thanks!



via Chebli Mohamed

Laravel: Address in mailbox given [] does not comply with RFC 2822

I send queued emails with my Laravel app. It usually works, however this one does not get out:

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. {"exception":"[object] (Swift_RfcComplianceException(code: 0): Address in mailbox given [] does not comply with RFC 2822, 3.6.2. at /is/htdocs/*****/www/memberportal/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php:354)

As far as I understand, it tries to send something to an empty email which of course not comply with RFC. This is the exact command that I found in the jobs table:

{
"displayName":"App\\Mail\\OrderSeals",
"job":"Illuminate\\Queue\\CallQueuedHandler@call",
"maxTries":null,
"timeout":null,
"timeoutAt":null,
"data":{
"commandName":"Illuminate\\Mail\\SendQueuedMailable",
"command":"O:34:\"Illuminate\\Mail\\SendQueuedMailable\":3:{s:8:\"mailable\";O:19:\"App\\Mail\\OrderSeals\":28:{s:9:\"firstLine\";s:14:\"Dear Max,\";s:6:\"paypal\";b:1;s:8:\"mainText\";
  s:121:\"enclosed your find your the attachment.\n\”This message was created automatically\"
  ;s:29:\"\u0000App\\Mail\\OrderSeals\u0000filePath\";s:99:\"\/is\/htdocs\/************\/www\/memberportal\/storage\/app\/document\/very_special.pdf\"
  ;s:29:\"\u0000App\\Mail\\OrderSeals\u0000subject2\";s:22:\"The document\";
  s:4:\"from\";
  a:0:{}s:2:\"to\";
  a:1:{i:0;a:2:{s:4:\"name\";s:15:\"Max Mustermann\";s:7:\"address\";s:21:\"max@gmail.com\";}}s:2:\"cc\";a:0:{}s:3:\"bcc\"
  ;a:0:{}s:7:\"replyTo\";a:0:{}s:7:\"subject\";N;s:11:\"\u0000*\u0000markdown\";N;s:4:\"view\";N;s:8:\"textView\";N;s:8:\"viewData\";a:0:{}s:11:\"attachments\";
  a:0:{}s:14:\"rawAttachments\";a:0:{}s:9:\"callbacks\";a:0:{}s:10:\"connection\";N;s:5:\"queue\";
  N;s:15:\"chainConnection\";N;s:10:\"chainQueue\";N;s:5:\"delay\";N;s:7:\"chained\";a:0:{}}s:5:\"tries\";N;s:7:\"timeout\";N;}"
 }
}

I do not fully understand the encryption. But I can see that address is set to max@gmail.com which is correct (real mail has been changed). Is maybe the cc or bbc set to an empty mail? Can I fix this command, so that the email will go out?



via Chebli Mohamed

Laravel Encryption/Decryption model data

I am working on a new project that stores guest information. For security I thought it would be cool to store all the personal data in the database with encryption. Is there any specific workflow for doing this. Essentially setting encryption on certain Model fields and having everything just work. Thinking about it, I feel like its not so simple but I thought I would throw it out there.



via Chebli Mohamed

Laravel 5.6 OnDelete cascade isnt working

I have been looking through other posts on here trying to figure this issue out, specifically the ones I linked at the bottom of the page. None of which have seemed to help me solve this issue. If this isnt allowed please remove and my apology's.

I have 3 different tables all of which have one to many relationships

servers->Incidents->incident_notes

I set the onDelete cascade for the foreign keys yet when I go to delete a server the incidents related to that i.d. stay. Below is the Migrations for the Tables as well as the destroy() methods. I am using laravel 5.6, on a wamp server, and using mysql and phpmyadmin!

servers table:

Schema::create('servers', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('url');
    $table->boolean('isPublic');
    $table->timestamps();
});

incidents Table:

Schema::create('incidents', function (Blueprint $table) {
    $table->engine = 'InnoDB'; 
    $table->increments('id');
    $table->string('title');
    $table->mediumText('body');
    $table->mediumText('status');
    $table->integer('server_id')->unsigned();
    $table->foreign('server_id')->references('id')->on('servers')->onDelete('cascade');
    $table->timestamps();
});

incident notes table:

Schema::create('incident_notes', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->mediumtext('body');
    $table->integer('incident_id')->unsigned();
    $table->foreign('incident_id')->references('id')->on('incidents')->onDelete('cascade');
    $table->timestamps();
});

Only posting one destroy because they are all pretty much the same code:

public function destroy($id)
    {
        $server = Server::find($id);
        $server->delete();

        return redirect('/dashboard')->with('success', 'Server deleted');
    }

Delete all posts related to a user in laravel

onDelete('cascade') has no effect Laravel 5.6

Laravel foreign key onDelete('cascade') not working



via Chebli Mohamed

Share on Facebook in laravel

I have shared a post from a website to the Facebook, it got shared but instead of the content that is in the post, my profile pic of that website got shared. Any help will be appreciated.



via Chebli Mohamed

Highlighting search results when using Laravel Scout

In my application, I am using Laravel Scout with the TNTSearch Driver to create a search bar in my site navigation, which is connected to a search method.

The search method searches a bunch of different models and returns what it finds to a view.

Here is the method:

/**
 * Perform a search given what the user entered into the search box.
 * Uses Laravel Scout to do initial search but because the use of WHERE is limited,
 * we use a filter function instead, on each collection.
 *
 * @param Request $request
 * @return void
 */
public function search(Request $request)
{
    // The search string entered
    $search = $request->get('q');

    // Laravel Scout search() method
    $users = User::search($search)->get();
    $articles = Article::search($search)->get();
    $events = Event::search($search)->get();
    $files = FileMetaData::search($search)->get();

    // The date and time as of right now
    $today = Carbon::now();

    /**
     * Below are the filters in place for each model search
     * 1. News articles must be open
     * 2. \Events are split into open and closed
     */
    $articles = $articles->filter(function ($articles) {
        return $articles->published === 'published';
    });

    $upcomingEvents = $events->filter(function ($events) use ($today) {
        return $events->startDate->gt($today);
    });

    $pastEvents = $events->filter(function ($events) use ($today) {
        return $events->startDate->lt($today);
    });

    $userCount = count($users);
    $articleCount = count($articles);
    $eventCount = count($events);
    $upcomingEventCount = count($upcomingEvents);
    $pastEventCount = count($pastEvents);
    $fileCount = count($files);

    return view('pages.search.index', compact('search', 'users', 'articles', 'upcomingEvents', 'pastEvents', 'userCount', 'articleCount', 'upcomingEventCount', 'pastEventCount', 'files', 'fileCount'));
}

As you can see, I'm using Scout's search() function to search each model and then put some additional constraints on the results, before returning them to my view.

The view itself

enter image description here

I would like the highlighted text at the top to also highlight where appropriate with the search results themselves but I can't seem to find anything in the documentation about using the TNT Highlighter class with Laravel.

Trawling through Laracasts forums, I found this: https://laracasts.com/discuss/channels/laravel/algolia-highlighting-in-laravel-53?page=1

Point of interest

<?php

use TeamTNT\TNTSearch\TNTSearch;

$articles = Article::search($searchString)->get();
$tnt = new TNTSearch;

$articles = $articles->map(function($article) use ($searchString, $tnt) {
    $article->title = $tnt->highlight($title, $searchString, 'em'),
});

In my case would I need this snippet for each result set?



via Chebli Mohamed

Why request is not passing to Nginx + Laravel basic auth?

I have a server with Nginx and Laravel. Laravel protect one special request with auth basic middleware

$router->group([

    'prefix' => 'special',

], function () use ($router) {

    $router->group([

        'middleware' => [ 'auth.basic', ],

    ], function () use ($router) {

        $router->get('/', 'SpecialController@index');
    });
});

If I'am getting https://example.com/special with browser - all ok. Browser request authorization from me, then pass to controller.

But if I'am emulate request with Postman, it is not working. Request performing is so long, I did not wait until the end.

Why it can happening? Earlier web server was Apache and request works fine.



via Chebli Mohamed

cropper js in laravel

my project is about to crop image then upload it to database and show it in controller. i saw a project about that but it upload the image to server

i tried for several days but i couldn't figure it out.

i use cropper js for that.

the image is shown in the view but i don't know how to pass it to my controller

        window.addEventListener('DOMContentLoaded', function () {
            var avatar = document.getElementById('avatar');
            var image = document.getElementById('image');
            var input = document.getElementById('input');
            var newavatar = document.getElementById('newavatar');
            var $modal = $('#modal');



            input.addEventListener('change', function (e) {
                var files = e.target.files;
                var done = function (url) {
                    input.value = '';
                    image.src = url;
                    $modal.modal('show');

                };
                var reader;
                var file;

                if (files && files.length > 0) {
                    file = files[0];

                    if (URL) {
                        done(URL.createObjectURL(file));
                    } else if (FileReader) {
                        reader = new FileReader();
                        reader.onload = function (e) {
                            done(reader.result);
                        };
                        reader.readAsDataURL(this.files[0]);
                    }
                }

            });
//important for cropping
            $modal.on('shown.bs.modal', function () {
                cropper = new Cropper(image, {
                    aspectRatio: 1,
                    viewMode: 3,
                });
            }).on('hidden.bs.modal', function () {
                cropper.destroy();
                cropper = null;
            });

            document.getElementById('crop').addEventListener('click', function () {
                var canvas;

                $modal.modal('hide');

                if (cropper) {
                    canvas = cropper.getCroppedCanvas({
                        width: 160,
                        height: 160,
                    });
                    newavatar.src = canvas.toDataURL();
                    canvas.toBlob(function (blob) {
                        var formData = new FormData();

                        formData.append('newavatar', blob);
                        $.ajax( {
                            method: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                        });
                    });
                    }
            });

        });

any one please help with this problem



via Chebli Mohamed

check the array value is set or nor

I'm fetching practice_string_id and program_string_id from a table

$project_type = DB::table('project')
              ->where('code',$asset_request->project_code)
              ->select('practice_string_id','program_string_id')
              ->first();
print_r($project_type); //output 
   stdClass Object ( [practice_string_id] => PRACTICE0028 [program_string_id] => )   

I want to check $project_type->program is set or not in if condition

if(isset($project_type->program_string_id)){
   //nothing in $project_type->program but reached here now 
 }

I want to how to check the value is set or not in php if condition



via Chebli Mohamed

setting up a jQuery load using a route and data parameter in Laravel 5

I have a route in my web.php file:

Route::get('noBodyDetail/{id}','VehiclesController@noBodyDetail')->name('noBodyDetail');

and in a datatables I am trying to establish a link using a javascript call:

<a href="#" onclick="showDetail()">@fa('eye')</a>

All OK so far.

My problem is calling the named route in a javascript function.

I have tried

 `function showDetail(id)
 {

   var url = "/" + id;
   $( "#detail" ).empty();
   $( "#detail" ).load( url );
 }`

But I am getting a missing parameter error

Missing required parameters for [Route: noBodyDetail] [URI: admin/noBodyDetail/{id}].

Can someone point out to me how to call a named route and passing a parameter in a javascript function?

Thanks!



via Chebli Mohamed

Get data from dropdown menu in laravel

  1. How can i get data from drop down menu

    Select Client @foreach ($clients as $client) - - - /- @endforeach

                                        </select>
    
    


via Chebli Mohamed

Is it possible to create multiple swagger documentation pages on one system Laravel?

I implement the swagger into the larvel project. I would like to create several api swagger documentation on one server. Each documentation pages will be for another system that provides own api. This server collects all data in one db of different systems. Is it possible to create multiple swagger documentation pages on one system?

Forexample:

https://ift.tt/2tMwEu1

https://ift.tt/2lGMDpP

https://ift.tt/2yPI3ik

Thanx



via Chebli Mohamed

Laravel 5 ovewrite helper function __() because used in wordpress

I have read several post on stackoverflow but didn't help, so i hope somebody can give the good answer.

I am using Laravel with wordpress. Now there is an error. Is it possible to rename or other method to change this?

Error:

Fatal error: Cannot redeclare __() (previously declared in C:app\laravel\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php:821)



via Chebli Mohamed

Get SMS history textlocal

I am using textlocal SMS gateway for sending SMS for my application.

Now i want history of sent SMS from account for that i am following the document of textlocal

For this i have done below code

    // Account details
    $apiKey = urlencode('Your apiKey');

    // Prepare data for POST request
    $data = array('apikey' => $apiKey);

    // Send the POST request with cURL
    $ch = curl_init('https://api.textlocal.in/get_history_api/');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    // Process your response here
    echo "<pre>"; print_r($response);

But i am getting

{"errors":[{"code":3,"message":"Invalid login details"}],"status":"failure"}

SO as per the API Documentation you should pass api key which i am sending in curl request still getting Invalid login details response.

Any help would be appreciated.

Thank you!



via Chebli Mohamed

check the user_id in the array

I have logged as approver_id ='897'. Request table have request_id,approver_id

request_id  approver_id
 005         897
 006         [897,91] 
 007         91 

I want to fetch the records where $approver_id is 897In a laravel query I have to get the row where the approver_id is 897 so expected 005 and 006

 $user=".."; //Query stuff
 $user=$user->where('request.flag','=','1')
 ->orwhereIN('asset_request.approver_id',array($approver_id))->get();

I didn't get any rows how to check the approver_idis in the table row



via Chebli Mohamed

Issue in displaying the data to view page in laravel, but the value is getting passed through url and its not getting displayed in the view page

Find below the controller code, Here I'm getting the data's passed in the url and I need the data entered through the form to be displayed / printed in the view page..

Controller Code:

public function create(Request $request)
     {
        $domainname = Input::get('domainname');
        $tld = Input::get('tld');
        $url='https://httpapi.com/api/domains/available.json?auth-userid=711757&api-key=74miSZPgYkkc108Ptmeo5Q8iDTtKk3xi&domain-name=';
        $ch = curl_init($url.$domainname.'&tlds='.$tld);
        711757&api-key=74miSZPgYkkc108Ptmeo5Q8iDTtKk3xi&domain-name='.$domainname.'&tlds='.$tld.'&suggest-alternative=true');
        $result = curl_exec($ch);
        $final_data = json_decode($result,true);
        dd($final_data);
        return view('clientlayout.main.tld',compact('final_data'));
}

tld.blade.php:

  

When I use the above code to print the data in view page, it just prints as "11".

Route code:

  Route::get('tld','TldController@create')->name('domain.create');

Kindly help me with this to solve the issue and print the data in the view page.



via Chebli Mohamed

mercredi 27 juin 2018

how do I inject user so I do not have to look him up in Laravel request

I am following a tutorial on laravel signed routes:

https://dev.to/fwartner/laravel-56---user-activation-with-signed-routes--notifications-oaa

To create the signed route author does this:

$url = URL::signedRoute('activate-email', ['user' => $this->user->id]);

notice that to the 'user' he only assignes the id...

Later when user in question clicks the generated link and another part of code does this:

Route::get('/activate-email/{user}', function (Request $request) {
    if (!$request->hasValidSignature()) {
        abort(401, 'This link is not valid.');
    }

    $request->user()->update([
        'is_activated' => true
    ]);

    return 'Your account is now activated!';
})->name('activate-email');

I am confused by this part:

    $request->user()->update([
        'is_activated' => true
    ]);

Author accesses user() directly and runs update on him?

When I in my own code tried this:

dd($request->user()) I got null and if I tried dd($request->user) I got user id number.

How is author able to call user()->update without looking up the user. I do not see where he does inject the User object, so it seems like magic to me or perhaps author did not test his own code fully, which is on github: https://github.com/fwartner/laravel-user-activation

So how do I inject the user into route so I do not have to explicitly look him up with

$user = User::find($request->user);



via Chebli Mohamed

Laravel Route Parameters Not Trimmed (it normally works with when whitespace is added)

I have the following route in web.php:

Route::get('posts/{encoded_id}/{slug}', 'PostController@show')

... and it works fine:

http://example.test/posts/1Dl89aRjpk/this-is-some-title

But the "problem" is that it will also work when I add a white space at the end of route parameter {encoded_id}:

http://example.test/posts/1Dl89aRjpk /this-is-some-title

// or

http://example.test/posts/1Dl89aRjpk%20 /this-is-some-title

// or

http://example.test/posts/1Dl89aRjpk%20%20 /this-is-some-title

With whitespace added at the end - this will work normally and there is no 404:

Post::where('encoded_id', $encoded_id)->firstOrFail();

... but why?

Maybe because of the type of field in the DB (CHAR)?

$table->char('encoded_id', 10)

Or maybe it has something to to with .htaccess (I'm using XAMPP / Windows)?

I'm using Laravel 5.6.



via Chebli Mohamed

how to send message with abort in Laravel

I've got to abort something if signature is not valid and I also would like to send a message to the view that renders it. I remember being able to do something like this in a previous project of mine, a year ago. But now when I try this

    if (!$request->hasValidSignature()) {
        abort(401, 'Signature is not valid.');
    }

I get an error that mentions that $message is not available

this is definition of the abort function, so its clear that it takes the message as input.

public function abort($code, $message = '', array $headers = [])
{
    if ($code == 404) {
        throw new NotFoundHttpException($message);
    }

    throw new HttpException($code, $message, null, $headers);
}

I wonder why do I get this error then:

ErrorException (E_ERROR)
Undefined variable: message (View: 
C:\laragon\www\laraone\resources\views\errors\401.blade.php)

this is a part of my 401.blade.php that uses that variable...

<div class="content">
    <div class="title">401</div>Unauthorized action, 
</div>



via Chebli Mohamed

Eloquent models comparation troubles

I have some difficulties with eloquent models in use-case like that:

$skill1 = new Skill();
$skill1->title = "Test";
$skill1->save();

$skill3 = Skill::findOrFail($skill1->id);

$this->assertEquals($skill1, $skill3);

Asserting gives error, because objects are not equals Comparasion result here In case we getting object from relation there are lots of new fields (e.g. original->relation)

I know, that there is "is" method in Eloquent models and it works right, but if I need to use core PHP function like in_array (for example, it is using in Collection's "contains" method), comparasion will not work.

The question is "How to compare these two models and use it like that:"

$this->assertTrue(collect([$skill1])->contains($skill3));

Maybe I can overload compare operator, maybe I can make smthng like IComparable in C#?

Thanks.



via Chebli Mohamed

Laravel 3 Table Relationship

Can anyone help me how to display the product name? I have productquantity stored in my purchase record and now I want to display the product name in productquantity record.

I have 3 Tables

Purchaserecord - id - purchasenumber - prodquantityid

Productquantities - id - prod_id

Product - id - productname

I have this in my controller

public function createpurchase(Request $request)
{
        $purchasenumber = $request->purchasenumber;
        $dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)->with('productquantity')->get();
        return view('admin.createpurchase',compact('purchasenumber', 'dataPurchaseRecord')); 

}

In my view

@forelse($dataPurchaseRecord as $Request)
              <tr>
                <td> <a class="name"></a></td>
                <td><em class="productprice"></em>  </td>
                <td style="width:100px;" class="td-actions"><a href="javascript:;" class="delete-modal btn btn-mini btn-danger" data-id="" ><i class="icon-minus"> </i>Remove</a> </td>
               </tr>
               @empty
               <tr><td colspan='4'><em>No Data</em></td></tr>
              @endforelse

in my model

 public function product()
{
    return $this->belongsTO('App\Product', 'prodquantityid', 'id');
}

this should be display the product name instead of the id How can I build the model and view on this? Please help.

Thank you



via Chebli Mohamed

Pass data between different "Via" Laravel Notification

Do you know how to pass data between 2 different "Via" notification? This is the situation: I have created 2 custom channels for notification

  1. PushNotificationChannel
  2. CustomDatabase

In my Notification Class I have this:

class GeneralNotification extends Notification
{
    use Queueable;

    private $notificationType;
    private $sender;

    public function __construct($notificationType, $sender)
    {
        $this->notificationType = $notificationType;
        $this->sender = $sender;
    }


    public function via($notifiable)
    {
        return [CustomDatabaseChannel::class, PushNotificationChannel::class];
    }

    public function toPushNotification($notifiable)
    {
        return [
            //
        ];
    }


    public function toCustomDatabase($notifiable)
    {
       return [
            //
        ];
    }
}

So this will first execute the toCustomDatabase method, and then the toPushNotification method.

What I want is after I save the data into de database, pass it (the inserted record) to the toPushNotification method.

I was testing with assigning for example:

public function toCustomDatabase($notifiable)
    {
       $this->notificationType = 'test';
       return [
            //
        ];
    }

but when I do:

public function toPushNotification($notifiable)
    {
        dd($this->notificationType);
        return [
            //
        ];
    }

It shows me the original notificationType, and not the value I changed in the toCustomDatabase method.



via Chebli Mohamed

Laravel 5.4 Spatie blade issue after deploying (probably a cache issue)

I have 02 env:

  1. local
  2. prod

Both have :

  • the same data, permission-role-user tables are populated by seeds
  • the same branch, and same version (git log returns the same last commit)

In fact, I tried to deploy last features which use new permissions and affect blade rendering. Below what I have in blade:

@can('manage_user’)

@endcan
@can('d_xxx’)

@endcan
@can('manage_manage_xxxx’)

@endcan

Locally, I have no issue

enter image description here

But in prod, Spatie seems ignoring existing permissions :(

enter image description here

I already tried those solution but without result:

  • php artisan config:clear
  • php artisan config:cache
  • php artisan view:clear
  • php artisan cache:forget spatie.permission.cache
  • restart the server

Has anyone faced this kind of issue, and what was the solution?



via Chebli Mohamed

Laravel: How to through 404 if the user enter the ID manually in the route?

Building an app (Blog/posts). Where only auth users can edit their post(which ofcourse belongs to them only). For example, Post with an id of 15 belongs to particular user, so the if he edits it, the route will be like this

http://localhost:8000/post/15/edit

this is correct.

But when the user enters any other post ID(which doesn't belongs to him) in the route, it shows

http://localhost:8000/post/16/edit

ErrorException (E_NOTICE)
Trying to get property 'user_id' of non-object

How to show unauthorised page in this case?



via Chebli Mohamed

composer global require "laravel/installer"

I'm having trouble asking you to help me install this error Laravel I'm a beginner I do not know where the problem is

[Composer\Downloader\TransportException]
The "http://packagist.org/p/provider-2013%24e48c5623bcfc80a0725d0e5e18083a9
2c1bb3b59e1591733c4ed8b07280b77d7.json" file could not be downloaded: faile
d to open stream: HTTP request failed!



via Chebli Mohamed

Mock classes on unit tests with Codeception and Laravel 5 module

In unit tests, this doesn't work:

class SomeClassCest
{
    public function tryToTest(UnitTester $I)
    {
        $mock = Mockery::mock(MyClass::class);
        $mock->shouldReceive('action')->once()->andReturn(true);
        $I->haveInstance(MyClass::class, $mock);

        $classToTest = app(SomeClass::class);
        // this method calls the MyClass action method
        $classToTest->run();

        // some asserts here
    }
}

The mock doesn't take effect, the $mock->action is never called, the real implementation is called instead. How to mock classes on unit tests with Codeception and the Laravel 5 module?



via Chebli Mohamed

Vue custom v-model value doesn't update the value after getting it from axios get request

I have a component called "TextInput":

            <template>
            <q-input
                v-model="content"
                @input="handleInput"
                color="secondary"
                :float-label="floatLabel" />
        </template>

        <script>
            import { QInput, QField } from "quasar-framework/dist/quasar.mat.esm";
            export default {
                props: ['floatLabel', 'value'],
                data () {
                    return {
                        content: this.value
                    }
                },
                components: {
                    'q-field': QField,
                    'q-input': QInput,
                },
                methods: {
                    handleInput(e) {
                        this.$emit('input', this.content)
                    }
                }
            }
        </script>

I used this component in another component:

            <template>
            <card card-title = "Edit Skill">
                <img slot="img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAJeSURBVEhLzZVPSFRRGMVnKopI+odghFjWQDD05v8/dGCEaFEhbnwIQQTVol2rCHElQog7lwm6qdy0jBJpWQvBImgTEqGYoKIDYhS4qt9n38Qb5973ni7KA2fuPd937jt35t33JrKvUCqVjmaz2XI8Hm8qFArHmT8KS/ytehk7UqlUHPOzTCbzA36EDroNbsEnQcS/zFjWy5mRy+VuYaxiHIDNWo4wl6ANlb5g/VvfIAw3ZDfQ0dJfWIKi8uE4zil6LuuKon2DEonEMZpL6XT6ipbqsDOIi12EH/AnisViC/MqfK49exCN+xheqWyAN0huNN5FOAnlF/gMh+l3Sp+5b9AUu+tT2QBvEKfwMPMemXPR28wfy7wG3yCaa8lk8rzKBniDgmANkgCa6yqN8AYx3sX/xsB+6TOag2iM0phQaYQ3CL88V+5OUrefOp6byzSq+Xz+jJaM4AC049vEf8GPcv+MQRSn4UOVRnBIcixchfN4v1r4jf4vwmTj9UGIq/BLLBY7oiUj8IyxeEilEWymG88M0yj+WQI7/nQAhV6ac4xdWjKCRXfwzMMR/MMm0nvK+BO+gCvoE7p8G1GK9yguMG4/1TYQdg2f8U3tJdd5YH1M+NrnMFRV7hoE9MhfikpfHMC8xU5Oqg4NNnmWTW7K/5WW/IFZ3lcZlaHBBgfhmMpgYH5Jzk2VocG69/C6ymBglrf3u93+fKxb5aBcUhkM13UPEjTOwu+MtYfwtbatwL8B645yKHB6TrPDNIvlxflJy1bsOagGFpf/SZDcK4JKKq0gpKtSqRxS+b8QifwGm+z/Ksto7VkAAAAASUVORK5CYII=">
                <form class="clearfix" slot="form">
                    <bim-text v-model="skill.name" :floatLabel="input_label"></bim-text>
                    <q-btn
                        @click="edit"
                        icon="save"
                        size="14px"
                        color="secondary"
                        label="Save" />
                </form>
            </card>
        </template>

        <script>
            import { QBtn } from "quasar-framework/dist/quasar.mat.esm";
            import { Card, TextInput } from "../../base";
            import router from '../../../routes/routes';
            export default {
                data: function () {
                    return {
                        id: this.$route.params.id,
                        skill: {
                            name: ''
                        },
                        input_label: 'Skill Name'
                    }
                },
                components: {
                    'card': Card,
                    'bim-text': TextInput,
                    'q-btn': QBtn
                },
                methods: {
                    edit: function(){
                        axios.patch('/api/skills/'+this.id, {
                            name: this.skill.name,
                        }, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
                        .then(response => {
                        alert('success');
                        router.push({ name: "IndexSkills"});
                        }).catch(error => {
                            console.log('dd');
                        });
                    }
                },
                mounted() {
                    axios.get("/api/skills/"+this.id, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
                        .then(response => {
                            this.skill = response.data.data;
                        }).catch(error => {
                            alert('error')
                        });
                }
            }
        </script>

        <style scoped>
            .q-btn{
                float: right;
                margin-top: 20px;
            }
        </style>

As you can see, I created an skill object with empty property called name and I made an axios request to get the specified object using its id. In then function of the axios request skill should be updated but what happened was that the v-model still empty.

What would be the problem here? and how can I solve it?

Thanks in advance.



via Chebli Mohamed

Passing data to all views served by a controller in Laravel

I have a controller that has two methods, each serving up a different view:

class NavController extends Controller {
 public function posts()
 {
  $posts = Post::all();
  $tabs = Tag::all();
  return view('posts')->with('posts', => $posts, 'tags' => $tags);
 }
 public function users()
 {
  $users = User::all();
  $tabs = Tag::all();
  return view('users')->with('users', => $users, 'tags' => $tags);
 }
}

I wish to avoid writing the logic for retrieving and passing tags in each and every method and thus I am wondering if there is a way to retrieve the data in one place in the controller and then pass it by default to every view that is served up by this controller.



via Chebli Mohamed

How to set up cors in laravel 5.5?

I am doing project in reactjs and created api in laravel 5.5. My product manager told me to use cors library. I search alot and found so many library packages. Can you please suggest me the library which is more stable and reliable? And also simple to use. Thank You in advance.



via Chebli Mohamed