jeudi 7 octobre 2021

Trying to Save Comments but the application redirects me to an empty page

I've made a blog and now I'm trying to implement a comment section. I want it so that when the user tries to post, it's saves the comment and redirects the user to the same page. But when I write a comment and try to post it, the application redirects me to a different page. I'm learning how to make a blog with laravel, so I don't know when to use url and when to use routes. Here's the code that I've written.

@auth
        <div class="card ml-5 col-lg-8">
            <ul class="list-group list-group-horizontal">
                <h5 class="list-group-item active">
                    Comments
                <h5>
                <div class="card-body">
                <form method="post" action="">
                @csrf
                    <textarea name="comment" class="form-control py-5"></textarea>
                    <input type="submit" class="btn btn-primary mt-3">
                </div>
                    
            </ul>
        </div>
        @endauth
        <div class="card ml-5 col-lg-8">
            <h5 class="card-header mb-4">Comments<span class="badge badge-info ml-2"> </span></h5>
            <div class="card-body mt-3">
                @if($blog->comments)
                    @foreach($blog->comments as $comment)
                    <blockquote class="blockquote">
                        <p class="mb-0"></p>
                        <footer class="blockquote-footer">Username</footer>
                    </blockquote>
                    <hr>
                    @endforeach
                @endif
            </div>
        </div>

**BlogController**
function save_comment(Request $request,$slug,$id)
{
    $request->validate([
        'comment'=>'required',
    ]);
    $data = new Comment;
    $data->user_id=$request->user()->id;
    $data->post_id=$id;
    $data->comment=$request->comment;
    $data->save();
    return back();
}

**Routes**
Route::get('/blog/', [App\Http\Controllers\BlogController::class, 'index'])->name('blog');
Route::get('blogs/{slug}','App\Http\Controllers\BlogController@getArticles')->name('article.show');
Route::get('blog.update/{id}','App\Http\Controllers\BlogController@edit');
Route::put('blog.update/{id}','App\Http\Controllers\BlogController@update');
Route::post('save_comment/{slug}/{id}','App\Http\Controllers\BlogController@save_comment')->name('save_comment');
Route::get('/admin/blog', 'App\Http\Controllers\BlogController@getBlog')->name('admin.blog');

If there's someone willing to assist come up with a solution to this problem, please assist me. I think the problem lies where I've written the url lies. When I change the url to route, it gives me an error of route not defined. Route::resource('/blog','App\Http\Controllers\BlogController');



via Chebli Mohamed

Have run laravel docker shift from 5.3 to 5.4 and 5.4 to 5.5 with problems

When running composer update it works until @php artisan package:discover I then got: In ProviderRepository.php line 208: Class 'Barryvdh\Cors\ServiceProvider' not found
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I got Barryvdh\Cors\ServiceProvider class defined in app.php enter image description here

So php artisan does not work at all. So what could be the problem?



via Chebli Mohamed

mercredi 6 octobre 2021

How to switch between languages in laravell

I'm new to laravell and would like to understand how to switch between two Languages the best way.

My website only uses two languages. I want to build a simple language switcher. Here is my HTML -> Which should display the language that I want to switch to. Not show the current language.

For example. If i am on www.test.com/en my html says

            <a class="lang-switch">German</a>

So when i click on it i land on

www.test.com/de

And now my html should say

                <a class="lang-switch">English</a>

Here is how i do my language routing.

Route::get('/{locale?}', function ($locale = null) {
    if (isset($locale) && in_array($locale, config('app.available_locales'))) {
        app()->setLocale($locale);
    }

    return view('home');
});

Route::get('/{locale?}/contact/', function ($locale = null) {

    if (isset($locale) && in_array($locale, config('app.available_locales'))) {
        app()->setLocale($locale);
    }

    return view('contact');
});

I need this switch to work on both websites since it's a static nav bar.

I register my locales in my app.php file

        'available_locales' => [
        'English' => 'en',
        'German' => 'de',
    ],

I created a Language Controller but i'm not sure how to implement or use it correctly.

    class LanguageController extends Controller
    {
      public function switchLang($lang)
        {
          if (array_key_exists($lang, Config::get('languages'))) {
             Session::put('applocale', $lang);
          }
          return Redirect::back();
        }
    }


via Chebli Mohamed

I'm having trouble placing a variable in my controller

I created an ecommerce store using Laravel, where I added all the controllers and the routes which seem to be working well without any errors. But recently I've been trying to add other 'related products' to my website. But when I ran the website after adding it, I get the error

'Undefined variable:categories'.

I've already placed the routed in my controller and allocated it the variable product. The only thing I don't know is how I would add another variable to the controller. I've tried nearly everything but nothing seems to work up to now. Here's my code.

<!--Related Products-->
<div class="col-md-4">
            <ul class="list-group list-group-horizontal-md">
                <li class="list-group-item active">
                    Related Products
                <li>
                    @foreach($categories as $category)
                        <a href="" class="list-group list-group-horizontal-md list-group-item-action">
                            
                            ()
                        </a>
                    @endforeach
            </ul>
        </div>
<!--Related Products-->

Controller

public function show(Product $product)
{
    //
    return view('products.show')->withProduct($product);
}

//Category Model

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

public function getRouteKeyName(){
    return 'slug';
}

Routes

Route::get('/ourbooks', [App\Http\Controllers\OurbooksController::class, 'ourbooks'])->name('ourbooks');
Route::get('/category/products/{category}', 'App\Http\Controllers\OurbooksController@getCategoryProducts')->name('category.products');
Route::resource('/products','App\Http\Controllers\ProductController');
Route::resource('/orders','App\Http\Controllers\OrderController');

Can any help me and show me how to get rid of the error?



via Chebli Mohamed

Why does Laravel / Horizon create `queue:failed` processes that eat up memory?

We have recently encountered the problem that our laravel server creates many processes using the command php artisan queue:failed that take about 1.2 GB of RAM each and don't seem to resolve on their own.

htop looks like this:

htop output

It is entirely possible that this is some weird edge-case configuration that we inherited from the previous developers, but maybe somebody has encountered a similar problem.

The laravel version is 5.7, horizon is 3.7 on php version 7.2.34-23. The horizon config is (we assume the queue workers are started by horizon):

[
    'domain' => null,
    'path' => 'horizon',
    'use' => 'default',
    'prefix' => env('HORIZON_PREFIX', 'horizon:'),
    'middleware' => ['web', 'auth'],
    'waits' => [ 'redis:default' => 600 ],
    'trim' => [
        'recent' => 60,
        'recent_failed' => 4320,
        'failed' => 4320,
        'monitored' => 10080,
    ],
    'fast_termination' => false,
    'memory_limit' => 1024,
    'environments' => [
        'production' => [
            'supervisor-1' => [
                'connection' => 'redis',
                'queue' => ['high', 'normal'],
                'balance' => 'auto',
                'minProcesses' => 1,
                'maxProcesses' => 20,
                'maxJobs' => 1000,
                'maxTime' => 3600,
                'tries' => 1,
                'timeout' => 90,
                'sleep' => 3,
            ],
            'supervisor-2' => [
                'connection' => 'redis',
                'queue' => ['default'],
                'balance' => 'auto',
                'minProcesses' => 2,
                'maxProcesses' => 20,
                'maxJobs' => 1000,
                'maxTime' => 3600,
                'tries' => 1,
                'timeout' => 90,
                'sleep' => 3,
            ],
            'supervisor-3' => [
                'connection' => 'redis-long-running',
                'queue' => ['low', 'very low'],
                'balance' => 'simple',
                'minProcesses' => 1,
                'maxProcesses' => 10,
                'maxJobs' => 100,
                'maxTime' => 3600,
                'tries' => 1,
                'timeout' => 3600,
                'sleep' => 3,
            ],
        ],

        'local' => [
            'supervisor-1' => [
                'connection' => 'redis',
                'queue' => ['default'],
                'balance' => 'simple',
                'processes' => 3,
                'tries' => 1,
            ],
        ],
    ],
]

Update

Running php artisan horizon:terminate seems to kill the queue:failed processes. The problem seems to appear when running a ShouldQueue Job directly from php artisan tinker.



via Chebli Mohamed

how to convert sql query in laravel query?

Iknow this question is not asked well manner so i am sorry i have sql query this one

`SELECT
    c.*
FROM
    merchantlink m,
    company c,
    merchantlinkrelation mlr
WHERE
    (m.initiator_user_id = c.owner_user_id AND
     m.responder_user_id = 86 AND
     mlr.ptype='dealer')
     OR
    (m.initiator_user_id = 86 AND
     m.responder_user_id = c.owner_user_id AND
     mlr.ptype = 'dealer')
     OR
    (m.initiator_user_id = c.owner_user_id AND
     c.owner_user_id=86 AND
     mlr.ptype='dealer')
GROUP BY
    c.id;`

i wnat to convert it in php laravel query form so tried this query

$twowaycompany = DB::table('company')
            ->join('merchantlink','merchantlink.responder_user_id', 'company.owner_user_id')
            ->orWhere('merchantlink.initiator_user_id', 86)
            ->join('merchantlink','merchantlink.initiator_user_id', 'company.owner_user_id')
            ->orWhere('merchantlink.responder_user_id', 86)
            ->pluck('name')->toArray();

but i dont know sql and even i am not understanding how i convert it can some one help just convert sql query to laravel query?



via Chebli Mohamed

mardi 5 octobre 2021

Pass hidden id to next page when click on a link

I have multiple control plane tables, each control plane belongs to a cluster. When I clicked on any control plane, I will redirect to the control plane details page. I need access to cluster id.

Option 1: via route params

I can get that bypassing it via the route like so

/deployments/bng/cluster/{clusterId}/services/{cp}

My first URL param will be $clusterId ... but my route structure like this

/deployments/bng/services/{cp}

Option 2: via session

I would have used Session::put() and Session::get(), but base on my index page, it doesn't seem to fit that.

Option 3: via database ... store/query

I find that too expensive, I rather not go this route.

Option 4: via hidden input (HTTP POST)

I would have done via hidden input if this is a form submit or ajax calls, but it is not...

Is there another way to pass on the clusterId to the next page ?

enter image description here

Please kindly advise,



via Chebli Mohamed