jeudi 19 août 2021

How to pass condition in laravel 5 relation model

I am trying to get the data from group model but i am relate the student table new_group_id to group table id if it not null else connect the group_id to group table id.

public function grade(Builder $query){
       
        
        return $query
          ->when($this->new_group_id != 0,function($q){
              return $q->with('new_group_id');
         })
         ->when($this->new_group_id === 0,function($q){
              return $q->with('group_id');
         });
    }

But given the error is Argument 1 passed to App\Students::grade() must be an instance of App\Builder,

please help me to solve these error



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3CTZA65
via IFTTT

mercredi 18 août 2021

Access Laravel URL with ID only (Best approach)

My application is made in laravel 5.8, I want to ask about the best approach for a unique scenario where I want to display some of my customer profiles like

https://www.example.com/1234

I know that in laravel I have to give a unique identifier before the URL like https://www.example.com/profile/1234 so that it know which function to look for. But for some reason I have to build the above URL.

I tried it directly like:

Route::get('/{id}', 'ExampleController@myfunction')->name('profiler');

But this only works when I put it in bottom of my Routes file. If I place it somewhere in the middle or top. All other links like https://www.example.com/about-us stops working.

My Question is:

  • What is the best approach to achieve something like this. (Is it fine that I keep it in the bottom of the route file or will it be some kind of threat or any drawbacks to this approach?)
  • Should I use this approach or add a unique identifier instead.

I would really want to use the URL I mentioned in the start of the question.

Thank you all in advance for helping me.

Peace :)



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3gg2l7X
via IFTTT

Laravel 5.7: Is it possible to add direct a value in the table?

I was wondering, if it possible to add directly a value in the table. Because I would like that all with the value "1" are registered

Schema::table('games', function (Blueprint $table) {
        $table->integer('rankPosition', '1');
});

Update solution:

Schema::table('games', function (Blueprint $table) {
        table->integer('rankPosition')->default(1);
});


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3AS4Sgx
via IFTTT

How To Hide ID from url ?? Laravel

I want to hide id from URL

http://example.com/photo/1234/image-name

I want it to change like this

http://example.com/photo/image-name

Is that there any way to remove or replace id from url.

CONTROLLER:

public function show($id, $slug = null)
{
    $response = Images::findOrFail($id);

if (Auth::check() && $response->user_id != Auth::user()->id && $response->status == 'pending' && Auth::user()->role != 'admin') {
    abort(404);
} else if (Auth::guest() && $response->status == 'pending') {
    abort(404);
}

$uri = $this->request->path();

if (str_slug( $response->title) == '') {

        $slugUrl  = '';
    } else {
        $slugUrl  = '/'.str_slug( $response->title );
    }

    $url_image = 'photo/'.$response->id.$slugUrl;

Href

<a href=""/>

Route

Route::get('photo/{id}/{slug?}','ImagesController@show');


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3kaMA3w
via IFTTT

Laravel Cache - Attempt to read from a closed MaxMind DB

I'm using Laravel 5.8 and MaxMind GeoLite2-City.mmdb together with Reader (GeoIp2\Database\Reader).

This is how it look like:

public function checkWithoutCache(Request $request) {
    
    $reader = new Reader(storage_path().'/app/ipToCountry/GeoLite2-City-v2.mmdb');      
    $r      = $reader->city($request->ip());
    $reader->close();
    return $r;
}

Everything working ok. Now because our server deals with tons of requests that for each request we are loading the Reader with the GeoLite2-City-v2.mmdb file (70MB), we wonder if it's smart to leave it like that or adding the Reader object to laravel Cache in order to load it once and then use the cache so we will improve performance.

So we were trying to use Laravel Cache like the next example:

public function checkWithCache(Request $request) {
    
    $reader = \Cache::remember('geo_city_instance', now()->addDays(30), function(){
        return new Reader(storage_path().'/app/ipToCountry/GeoLite2-City-v2.mmdb'); 
    });
    $r      = $reader->city($request->ip());
    $reader->close();
    return $r;
}

But we got the next Exception:

BadMethodCallException Attempt to read from a closed MaxMind DB ( …/vendor/maxmind-db/reader/src/MaxMind/Db/Reader.php158)

Does anyone have a solution on how to add it to cache without exception?

Or we don't need actually need to add it to cache?

Please help, thanks!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3D0W4aa
via IFTTT

middleware not redirect to view

i have a problem with middleware

my middleware should redirect to a view if the logged in user has the column 'edad' = Null

User loggin DB: https://i.imgur.com/9UubPls.png

    <?php

namespace App\Http\Middleware;

use Auth;
use Closure;
use Illuminate\Http\Request;

class Personales
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::guest()) {
            return $next($request);
        }
        
        if ($request->route()->getName() == "completar" || $request->route()->getName() == "ucompletar") {
            return $next($request);
        }

        if (Auth::user() && Auth::user()->edad != null && Auth::user()->edad != "") {
            return $next($request);
        } else {
            return redirect('/completar');
        }
    }
}

i can't find the error because it doesn't work middleware

maybe i'm missing something, just create middleware and view



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3k9ZZc6
via IFTTT

mardi 17 août 2021

Unit testing individual pieces of Laravel artisan commands without running the entire command

I have some pretty complicated commands with a lot of moving parts. I want to write tests for individual parts of those commands. This is proving to be a real pain the way I am currently doing it because the input and output interfaces are not instantiated until the run() method is hit during a typical programmatic call.

e.g.

Artisan::call('do:something', ['foo' => 'whatever', '--bar' => true]);

As such, I've written most of my tests like so:

protected function setUp()
{
    parent::setUp();

    $this->command = new DoSomething;
    $this->thing = Something::first();
}

/** @test */
public function it_succeeds_and_fails_at_doing_something()
{
    // Test happy path.
    $success = $this->command->verySuccess($this->thing->id);

    $this->assertInstanceOf(SomethingSuccessful::class, $success);

    // Test unhappy path.
    $failed = $this->command->verySuccess('nope');

    $this->assertNull($failed);
}

The problem with the above is that within the command's code is scattered calls such as if ($this->option('bar')) { ... } which always fails with Call to a member function getOption() on null

Aside from the exception, it also makes it problematic to test these specific methods with the right options and arguments set.

How do I get around this input issue? Feels like I am going about testing this the wrong way.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3CWxEhN
via IFTTT