samedi 1 juin 2019

Laravel middleware parameter error: undefined variable

I'm using Laravel 5.8 and I've created a middleware:

class ResourceMiddleware {
    public function handle($request, Closure $next, $resource){}
}

registered in kernel.php as

protected $routeMiddleware = [
    'resource' => 'App\Http\Middleware\ResourceMiddleware',
];

created a route like this:

Route::get(
    '/resource', 
    [
        'middleware' => 'resource:test', 
        'uses' => function() {
            return 'My resource';
        }
    ]
);

When I access GET /resource I got an error: undefined variable Somehow Laravel expects that the param name in ResourceMiddleware class should be $test. If I change the param name to $test, no error haapens and the $test value will be "test". What I'm doing wrong?

I tried different syntax like 'middleware' => ['resource:test'] or ->middleware('resource:test'). None worked.

There's a syntax that defines the param name and value? The documentation states that the syntax is middleware:value. Why the param name should be equals to value?

Best regards.



via Chebli Mohamed

laravel 5.8 Auth/RegisterController custom redirect on validation failure

I'm using Laravel 5.8, I have a single page that has both the Registration and Login forms (2 separate forms posting to the respective endpoints/controllers)

My Registration Form posts to the Auth/RegistrationController as provided by Lavarel Auth.

I would like to change the behaviour so that on an unsuccessful registration attempt it will add an additional parameter to redirect url so I know which form to apply to validation feedback too.

I'm already aware of the redirectTo variable this appears to be for successful requests though



via Chebli Mohamed

Update table columns without id in laravel

I want to create a page for admin where the page is only used to display data and update data. I create a table in the database without using an ID, because I don't want to create new data and only want to have one data other than that it can update that data.

this is my route

Route::group(['prefix' => 'admin', 'middleware' => ['web']], function () {
    Route::get('about', 'AboutController@index');
    Route::post('about/update', 'AboutController@update');
});

this is my model

public $timestamps = false;
protected $primaryKey = null;
public $incrementing = false;
protected $fillable = ['description'];

this is my controller AboutController.php

public function index()
{
    $data = About::first(); 
    return view('config_about.index', compact('data'));
}

public function update(Request $request)
{
    $this->validate($request, [
       'description' => 'required'
    ]);

    $data= About::first()->update($request->all());

    return redirect('admin/about');
}

and this is my form

{!! Form::open(['url' => 'admin/about/update', 'method' => 'post', 'class' => 'form-horizontal']) !!}
    <div class="form-group ">
        <div class="col-md-12">
            {!! Form::textarea('description', $data->description, ['class' => 'form-control']) !!}
            {!! $errors->first('description', '<p class="help-block">:message</p>') !!}
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-2 col-md-offset-0">
            {!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
        </div>
    </div>
{!! Form::close() !!}

I hope the results can update the data but what I get is an error like This page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500



via Chebli Mohamed

To select data from one table based on data from another table

I want to get the unavailable data in one table(schedules table) based on a list of existing data on another table(Classroom)

This is the schedules

CourseCode

Day

ClassroomID-->Fk from Classroom Table (ClassID)

PeriodID

This is the Classroom Table

Capacity

ClassID (PK)

BuildingName

I have thought of using an inner join and then find a NotIn of the results but I really don't know how to go about it

I expect to see all the Buildings which are available on a particular day at a particular period



via Chebli Mohamed

Laravel: dynamic drop down using jax not returning data

I'm trying to use ajax dynamic dropdown list from the database. so here is the Scenario i want:

-If i select a schedule in the dropdown select i want all related buses to that schedule to populate on that lower bus dropdown.

enter image description here

so far i was having everthing right! i mean i tested that data canbe passed to the controller, also Controller returned the json of the data. But when i tried to populate the select Bus options to the html in the success funcitoin nothing come up up to the bus dropdown.

I don't know what i missed, but sure there's an issue

View

[![enter image description here][2]][2]

here's theScript

<script type="text/javascript">
$(document).ready(function(){

    $(document).on('change','.schedule',function(){
        // console.log("hmm its change");

        var id=$(this).val();
        // console.log(id);
        var div=$(this).parent();

        var op=" ";
  // console.log(div);


        $.ajax({
            type:'get',
            url:"",
            data:{'id':id},
            success:function(data){
                //console.log('success');

                //console.log(data);

                op+='<option value="0" selected disabled>chose Bus Number</option>';
                for(var i=0;i<data.length;i++){
                  op+='<option value="'+data[i].id+'">'+data[i].bus_number+'</option>';
              }

              div.find('#busnumber').html(" ");
      // console.log(div);
              div.find('#busnumber').append(op);
      // console.log(div);



            },
            error:function(){

            }
        });
    });
});
</script>

Controller

public function getBusStation(Request $request)
{ 
    $id = $request->id;
    $queue = Schedule::find($id)->queue;

    $data = $queue;  
    return Response()->json($data);
}



via Chebli Mohamed

PHP / LARAVEL 5 ErrorException in MainController.php

all. I have problems after making some new steps. I'm rails developer, but now i have to do some support in php/laravel project. After making some UI + backend in project(adding OpenGraph in project + admin) - i made a command - php artisan migrate:fresh. And now i have this code error.

(1/1) ErrorException Trying to get property 'title' of non-object

in MainController.php line 78

MetaTag.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Setting
 *
 * @mixin \Eloquent
 */
class MetaTag extends Model
{
    /**
     * @var array
     */
    protected $table = "meta_tags";
    protected $fillable = ['title', 'description', 'keywords','og_type','og_title','og_description'];

}

part of MainController.php




<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use App\Http\Requests;

class MainController extends Controller
{
    public function index()
    {
        $main_banner = \App\Banner::where('type', '1')
            ->where('page', '1')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->first();

        $premium_blocks = \App\Banner::where('type', '2')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->get();

        $active_animations = \App\Setting::where('alias', 'anumations_active')->first();
        $active_films = \App\Setting::where('alias', 'films_active')->first();
        $active_games = \App\Setting::where('alias', 'games_active')->first();
        $active_heroes = \App\Setting::where('alias', 'heroes_active')->first();
        $active_news = \App\Setting::where('alias', 'news_active')->first();
        $active_soundtracks = \App\Setting::where('alias', 'soundtracks_active')->first();

        $animations = \App\Animation::where('active', '1')
            ->orderBy('order', 'asc')
            ->get();
        $films = \App\Film::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $games = \App\Game::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $heroes = \App\Hero::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $news = \App\News::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $soundtracks = \App\Soundtrack::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();

        $arr_month_rus = \Config::get('settings.arr_month_rus');
        $arr_month_rus_lower = \Config::get('settings.arr_month_rus_lower');
        $arr_games_types = \Config::get('settings.arr_games_types');
        $arr_news_types = \Config::get('settings.arr_news_types');

        $agent = new Agent();

        $browser = $agent->browser();
        $v = explode('.',$agent->version($agent->browser()));
        $version = $v[0];

        if (
            ($browser == "Internet Explorer" && $version > 10) ||
            ($browser == "Edge" && $version > 11) ||
            ($browser == "Firefox" && $version > 46) ||
            ($browser == "Opera" && $version > 38) ||
            ($browser == "Safari" && $version > 8) ||
            ($browser == "Chrome" && $version > 51)
        )
            $outdated = false;
        else $outdated = true;

        $meta_tags = \App\MetaTag::where('alias',  '=', 'main_page')->first();
        $title = $meta_tags->title;
        $description = $meta_tags->description;
        $keywords = $meta_tags->keywords;
        $og_title = $meta_tags->og_title;
        $og_description = $meta_tags->og_description;
        $og_type = $meta_tags->og_type;

        return view((($agent->isMobile()) ? 'mobile.home' : 'home'), compact(
            'main_banner',
            'premium_blocks',
            'animations',
            'films',
            'games',
            'heroes',
            'news',
            'soundtracks',
            'active_animations',
            'active_films',
            'active_games',
            'active_heroes',
            'active_news',
            'active_soundtracks',
            'arr_games_types',
            'arr_month_rus_lower',
            'arr_news_types',
            'arr_month_rus',
            'outdated',
            'title',
            'description',
            'keywords',
            'og_title',
            'og_type',
            'og_description'
        ));
    }

I expect just solve this little problem. Thanks!



via Chebli Mohamed

Table does not render (Yajra Datatables)

So, this is my controller:

use Yajra\DataTables\Facades\DataTables;
class CategoriasController extends Controller
{
    public function index()
    {
        return Datatables::collection(Categoria::all())->make(true);
    }
 [...]
}

this is my route:

Route::group(['middleware' => 'auth'], function () {
    Route::group(['middleware' => 'admin'], function () {   
        Route::prefix('admin')->namespace('Admin')->group(function () {
            Route::prefix('categorias')->group(function(){
                Route::get('/', 'CategoriasController@index')->name('curso.index');
[...]
             });
         });
     });
});

and this is my blade:

[...]
<div class="container">
    <table class="table border" id="myTable">
        <thead>
            <tr>
                <th>id</th>
                <th>Nome</th>
                <th>Criado</th>
                <th>Modificado</th>
            </tr>
        </thead>
    </table>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready( function () {
    $('#myTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{!! route('categoria.index') !!}',
        columns: [
                { data: 'id', name:'id'},
                { data: 'nome', name:'nome'},
                { data: 'created_at', name:'created_at'},
                { data: 'updated_at', name:'updated_at'},
            ]
    });
} );
</script>
[...]

And I got this as a return: Print

I'm using Laravel 5.8.19

composer.json

[...]
"require":{
        "yajra/laravel-datatables": "^1.5",
        "yajra/laravel-datatables-oracle": "~9.0"
}

So why is not a table rendering? Is it something I'm doing wrong? I ran the internet and I did not find a solution, I hope you will help me



via Chebli Mohamed