RomainB

RomainB

Member Since 3 Months Ago

Toulon

Experience Points
7,530
Total
Experience

2,470 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
40
Lessons
Completed
Best Reply Awards
4
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 2
7,530 XP
Nov
11
6 days ago
Activity icon

Started a new Conversation Resource On Freshly Created Model > Related_id In Pivot Undefined

Hi.

I have two models: Website(parent) and Keyword(child), with a ManyToMany relationship.

In [email protected] and update call, I want to return the website_id. I use firstOrCreate to not duplicate keyword rows in my database.

But I just get an error from the resource file: Trying to get property 'website_id' of non-object

Here is my KeywordResource class toArray function:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'text' => $this->text,
            'website_id' => $this->pivot->website_id
        ];
    }

And here is how I create the Keyword model, related to the Website one and return the KeywordResource:

public function store(Request $request, Website $website)
{
    $keywords = collect([]);
    
    foreach ($request->all() as $keyword) { // $request->all() contains an array of keywords values
        $keywords->push($website->keywords()->firstOrCreate($keyword));
    }

    return KeywordResource::collection($keywords);
}

any suggestions?

Activity icon

Replied to Using WithCount('a')->having('a_count', '=', 0)->delete() Erase All The Table!

@nakov It works as expected! Thanks. There are so many helpers in Laravel... I didn't know this one.

@jlrdw The SQL is really "DELETE from Keywords" - I looked in telescope

I tried something else to understand what causes that, I think it's having too:

Keyword::withCount('websites')
            ->having('websites_count','=', 1)
            ->delete();

It also deletes all the rows from the table...

Nov
10
1 week ago
Activity icon

Started a new Conversation Using WithCount('a')->having('a_count', '=', 0)->delete() Erase All The Table!

Hi.

I've got an issue which is pretty weird. I have two models with ManyToMany relationship: Website and Keyword.

I'm using [email protected] to "detach" the relation from the Website model, then I want to delete unused Keywords from the database.

I would use:

public function destroy(Website $website, Request $request)
{
    $website->keywords()->detach($request->all()); // IDs are passed as an array [1, 2, 3]

    Keyword::withCount('websites')
        ->having('websites_count','=', 0)
        ->get(); // Works as expected, returns just some rows

    Keyword::withCount('websites')
        ->having('websites_count','=', 0)
        ->delete(); // DELETE all rows from the table!
}

The problem is Laravel just performs a "DELETE FROM keywords" (seen in Telescope) so the table is just like truncated (except that the primary key isn't reinitialized).

What is weird is when I do the same query with get() instead of delete(), I get what I expect: just some rows, not the entire table!

Why?

Activity icon

Replied to Auto Injection In Middleware Constructor Doesn't Work?

It works fine:

Collection {#534 ▼
  #items: array:1 [▼
    0 => Website {#533 ▼
      #guarded: []
      #connection: "mysql"
      #table: "websites"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▶]
      #original: array:7 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
    }
  ]
}

But I don't understand why dependency injection doesn't work in this use case?

Activity icon

Started a new Conversation Auto Injection In Middleware Constructor Doesn't Work?

Hi, I'm trying to use middleware to check in an API context if the OAuth connected user is the owner of the "parent" resource needed.

My models' structure is like: Website | --------Aliases | --------Keywords

when someone calls API for an alias or keyword, I want to verify if the owner of the website is the one authenticated.

API Route always provides a website, like:

POST | api/keyword/{website}

And here is my middleware

<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Website;

class CheckPropertyOfWebsite
{

    protected $website_owner;

    public function __construct(Website $website)
    {
        $this->website_owner = $website->user;
        dd($website);
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->user() !== $this->website_owner) {
            return response(null, 500);
        }
        return $next($request);
    }
}

the dd in construct function always returns an empty Website object. So I'm not able to check the owner of it. Why?

Thanks!

Nov
09
1 week ago
Activity icon

Started a new Conversation API Resource: Id Of Relation Isn't Returned When Freshly Created

[EDIT] Found the solution by retrieving the Keyword model from the database

$keyword = $website->keywords()->create([
    'text' => $request->input('text')
]);

return new KeywordResource($website->keywords()->find($keyword->id)); // From database

Hi all, I'm working on an API with some relationships, for example, a "Website" model and a "Keyword" one

In [email protected], I create the model with "relationship call":

    public function store(Request $request)
    {
        $user = $request->user();
        $website = $user->websites()->findOrFail($request->input('website_id'));

        $keyword = $website->keywords()->create([
            'text' => $request->input('text')
        ]);

        return new KeywordResource($keyword);
    }

and here is my resource:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'text' => $this->text,
            'website_id' => $this->pivot->website_id
        ];
    }

My problem is website_id is not provided on the JSON response, why? and how to do so?

In [email protected], it works correctly:

    public function index(Request $request)
    {
        $user = $request->user();
        $website = $user->websites()->findOrFail($request->input('website_id'));
        
        return KeywordResource::collection($website->keywords);
    }
Nov
07
1 week ago
Activity icon

Started a new Conversation Is There A Passport Log? I Can't Create Any Token And Error Message Is Dummy ;/

Hi all. I made a simple mistake: after testing my app, I wanted to clear my database so I clear the passport table in my database.

And boom! I can't create any token with the Passport frontend scaffold anymore.

I just get an error message like "Whoops! Something went wrong!" in passport vue component. What an error message!

I tried to remove passport:

  • Delete the passport line in composer.json
  • Call a "composer update" to remove passport files
  • Artisan migrate:rollback to drop tables.
  • Delete oauth keys in storage folder

Then re-install it:

  • composer require laravel/passport
  • php artisan migrate
  • php artisan passport:install

But I still get this dummy error message...

Any idea where to start to debug?

Nov
06
1 week ago
Activity icon

Started a new Conversation Passport Bearer Auth: Laravel Responds A 200 But I Still Have A CORS Issue In Front End

[EDIT]Ok, it was an apache/laragon config issue: added Header set Access-Control-Allow-Origin "*" at the end of my httpd.conf, verify mod_header.so is activated and it's fine

Hi all, I'm trying to connect an API with a VueApp directly with a bearer token generated by Laravel Passport.

I installed barryvdh/cors package and modified Passport routes in my AuthServiceProvider:

Route::group(['middleware' => 'cors'], function() {
    Passport::routes();
});

When I try to access to /api/user with my Vue application with axios:

axios.get(
    'https://mazdigital.loc/api/user',
    { headers: {Authorization: "Bearer ".concat(token) } }
)

console still get a cors policy issue:

Access to XMLHttpRequest at 'https://mazdigital.loc/api/user' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js?b50d:172

But when I'm looking into Laravel Telescope, everything was fine:

GET     /api/user   200     274ms   7s ago
OPTIONS /api/user   200     263ms   7s ago

And the response for the GET is correct:

{
    id: 1,
    name: "user1",
    email: "user1[email protected]",
    email_verified_at: null,
    created_at: "2019-11-05 23:15:00",
    updated_at: "2019-11-05 23:15:00"
}

So why my App can't handle this response as a successful one?

Activity icon

Started a new Conversation Passport Fresh Install Fails On /oauth/authorize

[EDIT]... Tries over tries, and as usual: I found the problems when posted this post...

I just didn't check the "Require the client to authenticate with a secret." checkbox...

Hi all, I'm trying to implement Passport for my API.

For that I create a fresh install and followed the docs, everything was fine until I tried to access /oauth/authorize with my credentials.

Here I'm stuck with this error message:

{"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.","hint":"Code challenge must be provided for public clients","message":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed."}

I verified every parameter in the request url: https://mazdigital.loc/oauth/authorize?client_id=5&response_type=code&redirect_uri=http%3A%2F%2Flocalhost

Client id is ok, client redirect registered is: http://localhost (I tried to change it)

Any idea?

Oct
05
1 month ago
Activity icon

Started a new Conversation Which Open Source CMS Based On Laravel For A Web Agency Customization?

Hi all,

I'm working in a web agency and we are about to use an open source CMS project and customize it to create our client's websites. But don't know which one is the best solution.

We need a really simple base, projects we work on are pretty classics (hostel/restaurant/artisan homepages) and end users don't know anything about web development.

May someones post some feedbacks about the Laravel based CMS they used?

Thanks!

Sep
09
2 months ago
Activity icon

Replied to Adding Vue Element To Certain Pages Only.

What you need is stacks used this way: In your general template file in the head:

<html>
    <head>
        @stack('scripts')
    </head>
    <body>
        @yield("content")
    </body>
</html>

When you need to add your app:

@section('content')
    <div>Some HTML</div>
@auth
    @push('scripts')
        <script src="/example.js"></script> // You can use "defer" parameter here to load the script after page load.
    @endpush
    <div id="app"> //content </div>
@endauth
@endsection

With that: your scripts will be included properly in head and all of that only when auth.

TL;DR;

Personal tips: I use stacks for css and js in all my projects, so I'm able to load any assets files wherever in my blades templates and reduce page loading time by including only what is needed

@push('js')
    <script src="{{ asset('js/auditive-test.js') }}" defer></script>
    <script defer>function getLocationFromJS() { return {!! $location !!} }</script>
@endpush

@push('css')
    <link media="all" type="text/css" rel="stylesheet"  href="{{ asset('css/auditive-test.css') }}">
    <link media="all" type="text/css" rel="stylesheet"  href="{{ asset('css/auditive-test-graph.css') }}">
@endpush
Sep
06
2 months ago
Activity icon

Replied to Function Update()

If I understand. You have already a record in database which must not interract with the one you are trying to save?

Maybe the equal in where hour start/end? If the database one end at 10pm and you are trying to save one which start at 10pm, you get your duplicate.

[EDIT] what I said is stupid: you never compare a start with a end hour. But obviously the problem is coming from there. You must compare end with start to see if they intersect together: https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap

Sep
04
2 months ago
Activity icon

Started a new Conversation Use FirstOrCreate With WhereRaw To Compare Date?

Hi. I'm adding stats functionality on a list which display providers to my visitors to know how much it has been displayed.

I want to detail the stats for each week, so I want to create a new entry in database every week if it doesn't exist.

First, I used this logic:

$stats = ProviderStats::firstOrCreate(['provider_id' => $event->provider->id]);
if($stats->created_at->weekOfYear != Carbon::now()->weekOfYear)
    $stats = $event->provider->stats()->create();
$stats->increment('phone_displayed');
$stats->save();

It works But it create two ProviderStat in memory, and one is useless. Also I asked myself: "Is there a way to do it more fluently?". I know (for now) it's not possible to compare date in the firstOrCreate attributes comparison. So I tried to use whereRaw to do this:

firstOrCreate(['provider_id' => $event->provider->id])->whereRaw('WEEK(`created_at`) = '. Carbon::now()->weekOfYear)

But... It doesn't work :( the whereRaw is simply ignored!

I thinked: maybe I should create a "freshOrCreate" method? Or is there a way to compare date in firstOrCreateMethod?

Thanks for any suggestions.

[EDIT] Finally I can use fluent where and whereRaw directly into my event. The problem was the WEEK() SQL function which is different from Carbon::weekOfYear . I'm using WEEKOFDAY() SQL function and it's working.

For now I extended Model class with an abstract class Stat, which is implemented by my ProviderStat class, I still welcome any suggestions/agreements:

abstract class Stat extends Model
{
    public static function boot()
    {
        parent::boot();
    }
    /**
     * Get the first fresh(same week) record matching the attributes or create it.
     *
     * @param  array  $attributes
     * @return static
     */
    public static function freshOrCreate(array $attributes)
    {
        if ( ! is_null($instance = static::where($attributes)->whereRaw('WEEKOFYEAR(`created_at`) = '. Carbon::now()->weekOfYear .' AND YEAR(`created_at`) = ' . Carbon::now()->year)->first()))
        {
            return $instance;
        }

        return static::create($attributes);
    }
}
Sep
03
2 months ago
Activity icon

Replied to Query Which Works In SQL Client But Not In Laravel? SQL General Error 2031

[EDIT at the end of post]

Hi @jlrdw , thanks for your suggestion: Actually, except for construct my query, I'm already using DB facade to query the database with the last command:

$five_nearest_providers_query = DB::query()
->select(['name', 'phone', 'address_town', 'address_street', 'address_postal_code'])
->fromSub($five_nearest_towns, 'nearby')
->join('providers', 'providers.address_postal_code', '=', 'nearby.postal_code')
->distinct();

I tried to use pdo this way:

$five_nearest_providers_query = DB::query()
                                ->select(['name', 'phone', 'address_town', 'address_street', 'address_postal_code'])
                                ->fromSub($five_nearest_towns, 'nearby')
                                ->join('providers', 'providers.address_postal_code', '=', 'nearby.postal_code')
                                ->distinct()
                                ->toSql();
$database = DB::getPdo();
$final_query = $database->query($five_nearest_providers_query);
$result = $final_query->fetch();
dd($result);

But same exception occurs, without the error message:

PDOException (HY000)
SQLSTATE[HY000]: General error: 2031

It's very curious because when I copy/paste directly the result of the toSql() (retrieved by dd($five_nearest_providers_query), the query is working:

$final_query = $database->query("select distinct `name`, `phone`, `address_town`, `address_street`, `address_postal_code` from (select `postal_code` from `towns` order by ST_DISTANCE(`location`, (select `location` from `towns` where `postal_code` = $postal_code limit 1)) asc limit 5 offset 0) as `nearby` inner join `providers` on `providers`.`address_postal_code` = `nearby`.`postal_code`");

[EDIT] I targeted the problem, it came from the passed variable $postal_code in $visitor_town where clause:

->where('postal_code', $postal_code)

which then is submitted to the $five_nearest_towns orderBy:

->orderBY(DB::raw("ST_DISTANCE(`location`, (".$visitor_town->toSql()."))"), 'asc')

So the toSql() returned :

select location` from `towns` where `postal_code` = ? limit 1

The variable wasn't passed > Query crashed.

This is what I did to resolve the problem (final code):

$visitor_town = Town::query()
                ->select(['location'])
                ->whereRaw("postal_code = ".$postal_code) //<<<!!! Passed variable in a raw where clause
                ->take(1)
                ->toSql();
                            
$five_nearest_towns = Town::query()
                      ->select(['postal_code'])
                      ->orderBY(DB::raw("ST_DISTANCE(`location`, (".$visitor_town."))"), 'asc')
                      ->offset(10)
                      ->limit(5);

$five_nearest_providers_query = DB::query()
                                ->select(['name', 'phone', 'address_town', 'address_street', 'address_postal_code'])
                                ->fromSub($five_nearest_towns, 'nearby')
                                ->join('providers', 'providers.address_postal_code', '=', 'nearby.postal_code')
                                ->distinct()
                                ->get();

I needed to pass the variable in a raw expression, to ensure it was fully transmitted to the upper level query.

Sep
02
2 months ago
Activity icon

Started a new Conversation Query Which Works In SQL Client But Not In Laravel? SQL General Error 2031

Hi.

Following my previous post

I finally found how to "convert" my SQL raw query into Laravel query builder to be more eye-friendly and maintainable:

SELECT DISTINCT `name`, `phone`, `address_town`, `address_street`, `address_postal_code`
FROM (
    SELECT `postal_code`
    FROM `towns`
    ORDER BY ST_DISTANCE(`location`, (
        SELECT `location`
        FROM `towns`
        WHERE `postal_code` = 83390
        LIMIT 1)) ASC
    LIMIT 5 OFFSET 10) AS `nearby`
INNER JOIN `providers` ON `providers`.`address_postal_code` = `nearby`.`postal_code`

Became:

$visitor_town_query = Town::query();
$visitor_town = $visitor_town_query
->select(['location'])
->where('postal_code', $postal_code)
->take(1);

$five_nearest_towns_query = Town::query();
$five_nearest_towns = $five_nearest_towns_query
->select(['postal_code'])
->orderBY(DB::raw("ST_DISTANCE(`location`, (".$visitor_town->toSql()."))"), 'asc')
->offset(10)
->limit(5);

$five_nearest_providers_query = DB::query()
->select(['name', 'phone', 'address_town', 'address_street', 'address_postal_code'])
->fromSub($five_nearest_towns, 'nearby')
->join('providers', 'providers.address_postal_code', '=', 'nearby.postal_code')
->distinct();

When I make a $five_nearest_providers_query->toSql()->dd(), the query is exactly the same as expected, and even when I copy/paste this query from dd to my SQL Client (HeidiSQL 10.2): the query works perfectly!

But when I do $five_nearest_providers_query->get(), error occurs:

Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 2031 (SQL: select distinct `name`, `phone`, `address_town`, `address_street`, `address_postal_code` from (select `postal_code` from `towns` order by ST_DISTANCE(`location`, (select `location` from `towns` where `postal_code` = ? limit 1)) asc limit 5 offset 10) as `nearby` inner join `providers` on `providers`.`address_postal_code` = `nearby`.`postal_code`)

So... What may block Eloquent to query my database? I guess it may be a configuration or whatever not is this code but I don't know where to start my search.

Thanks!

Sep
01
2 months ago
Activity icon

Replied to Use InnerJoin With A "complex" SQL Request

Woaw... It was that simple...

It's still remain eye-unfriendly so if someone knows where to put my inner join...

[EDIT] I finally found solution, this is my final builder query:

$visitor_town_query = Town::query();
$visitor_town = $visitor_town_query
->select(['location'])
->where('postal_code', $postal_code)
->take(1);

$five_nearest_towns_query = Town::query();
$five_nearest_towns = $five_nearest_towns_query
->select(['postal_code'])
->orderBY(DB::raw("ST_DISTANCE(`location`, (".$visitor_town->toSql()."))"), 'asc')
->offset(10)
->limit(5);

$five_nearest_providers_query = DB::query()
->select(['name', 'phone', 'address_town', 'address_street', 'address_postal_code'])
->fromSub($five_nearest_towns, 'nearby')
->join('providers', 'providers.address_postal_code', '=', 'nearby.postal_code')
->distinct();
Activity icon

Started a new Conversation Use InnerJoin With A "complex" SQL Request

Hi all.

My goal is to retrieve nearest Providers model, located by longitude/latitude field contained in Towns table.

My tables are like:

Providers

`id` | `name` | `address_street` | `address_postal_code` | `address_town`

Towns ( where location is point field)

`id` | `name` | `postal_code` | `location`

The raw sql query is this:

SELECT `name`, `address_street`, `address_postal_code`, `address_town`
FROM (
    SELECT `postal_code`
    FROM `towns`
    ORDER BY ST_DISTANCE(`towns`.`location`, (
        SELECT `towns`.`location`
        FROM `towns`
        WHERE `towns`.`postal_code`= '83500'
        LIMIT 1)
    ) ASC
    LIMIT 5
) AS `nearby`
INNER JOIN `providers` ON `providers`.`address_postal_code` = `nearby`.`postal_code`
LIMIT 5

This query is working perfectly when submitted directly in database.

First I tried to use directly my raw query:

DB::query(DB::raw('
    SELECT `name`, `address_street`, `address_postal_code`, `address_town`
    FROM (
        SELECT `postal_code`
        FROM `towns`
        ORDER BY ST_DISTANCE(`towns`.`location`, (
            SELECT `towns`.`location`
            FROM `towns`
            WHERE `towns`.`postal_code`= '.$postal_code'
            LIMIT 1)
        ) ASC
        LIMIT 5
    ) AS `nearby`
    INNER JOIN `providers` ON `providers`.`address_postal_code` = `nearby`.`postal_code`
    LIMIT 5
'))->get();

But SELECT FROM SELECT seems to not work with DB::raw: SQLSTATE[HY000]: General error: 1096 No tables used (SQL: select *)

Also it's not really eye-friendly in my Laravel app. So I want to use Laravel builder facade. But Hmm... That's not so easy...

I tried some few things, but I'm not able to get the same query, especially the inner join:

$visitor_town_query = Town::query();
$visitor_town = $visitor_town_query
         ->select(['location'])
         ->where('postal_code', $postal_code)
         ->take(1); // Some nearby-towns may have the same postal code

$five_nearest_towns_query = Town::query();
$five_nearest_towns = $five_nearest_towns_query
                      ->select(['postal_code'])
                      ->orderBY(DB::raw("ST_DISTANCE(`location`, (".$visitor_town->toSql()."))"), 'asc')
                      ->take(5);

$five_nearest_providers_query = DB::query()
                                ->select(['name', 'phone', 'address_town', 'address_street', 'address_postal_code'])
                                ->fromRaw('('.$five_nearest_towns->toSql().')')
                                ->take(5);


return $five_nearest_providers_query->toSql();

I'm using toSql() function on $five_nearest_towns just to see what I need to add in my query. Here is the SQL request generated:

select `name`, `phone`, `address_town`, `address_street`, `address_postal_code` from (select `postal_code` from `towns` order by ST_DISTANCE(`location`, (select `location` from `towns` where `postal_code` = ? limit 1)) asc limit 5) limit 5

Where to place inner join?? I feel like I ran in a dead end and maybe I choose wrong way?

Aug
25
2 months ago
Activity icon

Replied to Profile Pages Don't Show Forum Activity

I've got the same here!

Aug
24
2 months ago
Activity icon

Started a new Conversation First Step In VueJS: Why V-anything Isn't Working But {{ Var }} Is?

Hi all.

I'm trying to include some vue in my Laravel project.

I used npm to install it. Vue chrome's extension detects it in my project, and I tried a simple hello world with:

new Vue({
    el: '#app',
    data: {
        name: 'hello world'
    }
});

and a simple call to this data with:

<p>{# name #}</p>

I changed the VueJS delimiters to not interfere with Blade's ones

This is working well!!

But, I tried a method which call a simple alert elsewhere with a simple @click and also v-on:click: I was unable to make it work.

Searched for hours, and then I tried something else: I returned to my hello world but wether use a {# name #} I used:

<p  v-html="name"></p>

And this is not working!!

Exact same file: {# name #} is working v-html="name" is not!!

Why?? I am unable to use any "v-directive"!

Any suggestions?

Activity icon

Replied to Run Yield Multiple Times

You should use stacks with a loop instead of yield:

In your website-layout.master:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

@stack('page-container')

</body>
</html>

In your pages which need multiple <section class="section-gap">:

@extends('website-layout.master')

    @foreach($some as $one)
        @push('page-container')
            <section class="section-gap">
                <div class="container">
                    SomeContent
                </div>
            </section>
        @endpush
    @endforeach

More on stack: https://laravel.com/docs/5.8/blade#stacks

Activity icon

Replied to Route Is Not Allowing Me To Use Id Parameter Instead Of One I Had Set Earlier

The problem may comes from elsewhere: if you are using routes like /tvdhow/{id}. You must pass an id into your view, if you are using named routes or just resource route. You can use route helper in your view links. Something like:

<a href="{{ route('tvshow.show', $tvshow->id) }}">Show {{ $tvshow->name }}</a>

And then in your controller use a findOrFail selector:

public function show(Request $request)
{
    TVShow::findOrFail($request->id);
}
Aug
23
2 months ago
Activity icon

Started a new Conversation HasMany(Child) And Return $this->where() In Child Model Doesn't Work

Hi.

Why this works:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class)->where('accepted', 1);
    }
}

With that call: $post->comments()->get();

But not this:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
class Comment extends Model
{
    public function accepted()
    {
        return $this->where('accepted', 1);
    }
}

With that call: $post->comments()->accepted()->get(); Exception is thrown: Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::accepted()

The goal is to put the ->where() method at the right place in my models: I need to filter comments, so the accepted() method should be in comment model.

Thanks for your suggestions.

Aug
22
2 months ago
Activity icon

Replied to Need Your Suggestion!

Vue.js is already in Laravel.

If it does the job. Why are you searching for something else?

Activity icon

Replied to How To Clarify My Controller Code. Controller Without Model.

Thanks for the advice.

I've never used Services or Service Provider until now.

So my next question is: what the architecture to have?

I viewed the Jeffrey Way course on Service Provider and read the documentation. About Service Provider they say: Within the register method, you should only bind things into the service container

So my ImageService Class should be in Service folder and a ImageServiceProvider should bind this class?

I'm pretty confused about Services and Services Providers...

[EDIT] For now I just created a ImageService, without Provider bindings:

<?php
namespace App\Services;

class UploadFileService
{
    public function getListOfFiles($dir, $format = 'TinyMCE', $with_extensions = 'ALL')
    {
        $list_uploaded_files = [];
        if(is_dir($dir)){
            if($open = opendir($dir)){
                while (($file = readdir($open)) !== false){
                    $img_path = $dir.$file;
                    if(is_file($img_path)){
                        $name = pathinfo($file, PATHINFO_FILENAME);
                        $list_uploaded_files[] = ['title' => $name, 'value' => asset('img/posts/'.$file)];
                    }
                }
                closedir($open);
            } else {
                return response("500: Can't open folder", 500);
            }
        } else {
                return response("500: It's not a folder, or it doesn't exist", 500);
        }
        return response()->json($list_uploaded_files);
    }

    public function storeFile($file)
    {
        $name = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $dir = public_path().'\img\posts\';
        $file->move($dir, $name);
        
        return asset('img/posts/'.$name);
    }
}

And Laravel resolves in my controller:

<?php

namespace App\Http\Controllers\AdminZone;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\UploadFileService;

class StoredFileController extends Controller
{
    public function __construct(UploadFileService $UploadFileService)
    {
        $this->middleware('auth');
        $this->UploadFileService = $UploadFileService;
    }
    
    public function index()
    {
        $images = $this->UploadFileService->getListOfFiles(public_path('img/posts/'));

        return $images;
    }

    public function store(Request $request) 
    {
        $uploaded_image_path = $this->UploadFileService->storeFile($request->file('file'));
        
        return response()->json(['location' => $uploaded_image_path]);
    }

For basic Service, I guess it's sufficient

Activity icon

Started a new Conversation How To Clarify My Controller Code. Controller Without Model.

Hi.

I've got a controller to manage endpoint for uploading image from TinyMCE.

For now its just two functions: store and index.

Index return a json list of images contained in the img folder:

    public function index()
    {
        $dir = public_path('img/posts/');
        $list_uploaded_img = [];
        if(is_dir($dir)){
            if($open = opendir($dir)){
                while (($file = readdir($open)) !== false){
                    $img_path = $dir.$file;
                    if(is_file($img_path)){
                        $name = pathinfo($file, PATHINFO_FILENAME);
                        $list_uploaded_img[] = ['title' => $name, 'value' => asset('img/posts/'.$file)];
                    }
                }
                closedir($open);
            } else {
                return response("500: Can't open folder", 500);
            }
        } else {
                return response("500: It's not a folder, or it doesn't exist", 500);
        }  
        return response()->json($list_uploaded_img);
    }

The function will grow up to handle subdirectories, filter image-only files, and so on... I want to clarify the controller to something like that:

    public function index()
    {
        return getListOfImage('dir');
    }

Image is not an Eloquent Model so I can't just add function to it. What is the best place to paste my getListOfImage function and how to include it in my Controller?

Aug
20
2 months ago
Activity icon

Replied to What Is The Best Way To Manage An Unregistered Visitor Rating System? Token? IP?

You are right. It's not a big deal if it's not perfect. It's just a rate system. Not a security one.

Thanks.

Activity icon

Replied to Online Quiz Application

  1. Route like question/{question} should do the work. Question/1, question/2, question/3 etc...

  2. Simple way: in [email protected] method, pass a variable time to the view with a now() method, store it in your view with a hidden field - or directly in your view, use now() method to fill the hidden field's value -. And in your [email protected] (when reply is sent), verify the value of the field.

  3. Less simple way: the same with session, so the visitor can't modify the html.

Activity icon

Replied to What Is The Best Way To Manage An Unregistered Visitor Rating System? Token? IP?

@rameezisrar Remember_token is associated with a registered user, I agree with you. But I could store another one, like csrf for example.

For now, I'm using twice:

$already_rated = $post->rates()
            ->where(function ($query) {
                $query->where('ip', request()->ip())
                ->orWhere('csrf_token', csrf_token());
            })->count();

So csrf_token "block" if visitor ip changes I guess ô_Ô

Don'tknow if csrf is changing when visitor's ip does? I'll give it a try it with a internet box reboot tonight.

Aug
19
2 months ago
Activity icon

Started a new Conversation What Is The Best Way To Manage An Unregistered Visitor Rating System? Token? IP?

Hi all, I want my website visitor to be able to tell me by two simple button if some post are 'Usefull' or 'Useless', like thumbs.

I know some packages could do this with some lines of code but I also want with this system to learn some relationship tricks.

Only my post will be "rateable", so I think I don't need a polymorphic structure.

What I have in mind:

Rate table with: a token cookie or an IP, or twice?? post_id rate (boolean: 1 = usefull, 0 = useless)

Rate model belongsTo Post Post model hasMany Rate

My question is: what is the best way to store "unique" visitor in my table? a token? the IP address of visitor? twice? something else? Maybe Laravel includes some magic tricks to catch "unique visitor which have already rate post"?

I welcome any advice which could help me.

Thanks.

Aug
17
3 months ago
Activity icon

Replied to Access Form Request From Observer

To cleanup your code, you can also clarify your Customer bank, document, company and relationship creation. And even the update: Laravel "auto-retrieve" from request the data if your inputs name is the same as you database field.

For example, this update will work:

Customer::where('user_id', Auth::user()->id)
            ->update([
                'title',
                'middlename' =>  isset($request->middlename) ? $request->middlename : "",
                'phone',
                'gender',
                'DOB',
                'marital',
                'residential_address',
                'city',
                'state',
                'lga',
                'nationality',
                'complete_registration' => 1 ]);

In my project I also included a "with_user_id" helper declared in "app\helpers.php":

    function with_user_id($array)
    {
        return Arr::add($array, 'user_id', Auth::id());
    }

which I use like this:

$post = Post::create(with_user_id($request->only(
      'user_id',
      'category_id',
      'comment_authorized',
      'header_image_url',
      'title_fr',
      'title_en',
      'header_image_title_fr',
      'header_image_title_en',
      'header_image_alt_fr',
      'header_image_alt_en',
      'seo_title_fr',
      'seo_title_en',
      'seo_slug_fr',
      'seo_slug_en',
      'seo_description_fr',
      'seo_description_en',
      'content_fr',
      'content_en'
)));
Activity icon

Replied to Build Wordpress Like CMS

I use Tinymce, which is pretty simple to manage into Laravel project: https://medium.com/@bvipul/integrate-tinymce-editor-in-your-laravel-installation-with-a-filemanager-235894910531

The text editor modify the textarea to insert bbcode/html button and even image uploader. Then you just have to parse the database output

Aug
16
3 months ago
Activity icon

Replied to [email protected] With A Call To $this->anotherAction() Isn't Working?

Woaw. It's just... The shame...

Is that possible to delete this post? Lol

Activity icon

Started a new Conversation [email protected] With A Call To $this->anotherAction() Isn't Working?

Hi. To manage post on a blog website, I've got a high-level category named "Blog" displayed on /blog/, and some others categories displayed on root directory with the uri /category/{category}.

To display category's post I've got a CategoryController with show() method:

    public function show(Category $category)
    {
        $posts = $category->posts;
        return view('public.post.index')
                ->with('posts', $posts);
    }

And to display "blog" post, I've got a blog() method, which to DRY my code, call $this->show() method:


    public function blog()
    {
        $category = Category::findOrFail(1);
        $this->show($category);
    }

I've got the routes: /category/{category} to display all categories's post, and /blog/ to filter only the post where category_id = 1

Don't know if it's the better way to do this (I could probably simply filter /blog/ uri in my show() method) but this isn't the question.

In fact I'M just surprised to see that $this->show($category) in my blog() method, works (tested with dd()) but the return view isn't! Only a white page is rendered when /blog is requested

My posts table for now just have 4 rows, all for /blog/ so the root uri: /category/1 and /blog should be the same.

I tried to dd($posts) > in the show() method > The 4 rows are properly return in both ways (/blog and /category/1). So why the view() method silently screw up on /blog request?

Aug
10
3 months ago
Activity icon

Replied to How To Properly Install Package?

@eslamahmed Thanks for the link, but my choice is made for ContentTools. Even if it's not the simplier to install.

My question concerns also future libraries that I may want to include in my projects. What the proper way to install package?

Activity icon

Started a new Conversation How To Properly Install Package?

Hi all, I want to install the WYSIWYG editor ContentTools on my Laravel project.

But I'm not very sure how to do it and I'm afraid to pollute my project's folder with useless files.

I search over the web. It seems I need to install NodeJS then npm, then grunt, then git, then.... woaw????!!!

Does them all are necessary to just install a text editor?

What's the correct procedure to install this type on library on my project?

Thanks for advice.

Activity icon

Commented on Simpler Debugging With Laravel Telescope

I had exactly the same problem, using Xampp on windows: Telescope wasn't working at all: I was able to load Telescope with the normal path: localhost/myproject/public/telescope

But I observe that every links in the menu was wrong: localhost/telescope/queries, localhost/telescope/requests, etc...

So I guessed that path crashed all telescope. I tried to modify the .env file to set the TELESCOPE_PATH, but all my attempts were futile: telescope home page became localhost/myproject/public/myproject/public/telescope, other link was corrects but telescope wasn't watching at all.

I saw in this tutorial that Jeffrey was using Virtual Hosts, so I tried this out and configure my Xampp server to listen on "myproject.local". And it worked!

Telescope is now fully working on myproject.local/telescope and all links are corrects!

To set virtual hosts on Xampp server on Windows 10, go at: https://www.cloudways.com/blog/configure-virtual-host-on-windows-10-for-wordpress/

The tutorial was made for Wordpress but it work for all installations.

Aug
09
3 months ago
Activity icon

Replied to ReflectionException (-1) Class Post Does Not Exist

Damn!!!! I got it!!!!

Entirely my fault. In web.php i binded the Post model:

// route–model binding
Route::model('post', 'Post');

I don't even know why!

Thanks you all for your time.

Activity icon

Replied to ReflectionException (-1) Class Post Does Not Exist

Thanks for help, but again the problem is not here :cry:

I tried with a fresh model and exception occurs:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
}

And i don't think namespace is required, my Category model works properly:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $guarded = [];

    public function children()
    {
        return $this->hasMany('Category', 'parent_id');
    }
    
    public function parent()
    {
        return $this->belongsTo('Category', 'parent_id');
    }
    
    public function posts()
    {
        return $this->hasMany('Post');
    }
}
Activity icon

Replied to ReflectionException (-1) Class Post Does Not Exist

@munazzil Thanks for the compact function but it doesn't help. Problem occurs also in destroy function which can't be more simplier:

    public function destroy(Post $post)
    {
        $post->delete();
        return redirect()->route('admin::post.index');
    }

I also clean all my controller, error occurs with this:

<?php

namespace App\Http\Controllers\AdminZone;

use App\Post;
use App\Category;
use Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\PostStoreUpdateRequest;

class PostController extends Controller
{
}

It isn't a syntax error... Problem occurs when Laravel need to load a post at HTTP request's moment: destroy, edit and probably update (can't submit edit's form for now...)

Activity icon

Replied to How To Dry Up This Part Of My Code?

@erikverbeek > Woops. Miss that part.

@clevonnoel > Agree with you but everybody makes with his capabilities.

@nabilunfarhanun > What I would do in this case. Filter "accepted forms" with a simple class .thisFormCanCallAjax on forms, and errors in class instead of unique id. And then just retrieve the ID of form which is submitted with form.attr('id')

$("form.thisFormCanCallAjax ").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var formId = form.attr('id');
    var url = form.attr('action');
    $.ajax({
        type: "POST",
        url: url,
        data: $(formId).serialize(),
        success: function(data)
        {
            if(data=="success")
            {
                location.reload();
            }
            else
            {
                var html = "<ul>";
                for(var dat in data)
                {
                    for (var x in data[dat])
                    {
                        html = html+"<li>"+data[dat][x]+"</li>";
                    }
                }
                html = html+"</ul>";
                $(formId +" .errors").attr("class","alert alert-danger");
                $(formId +" .errors").html(html);
            }
        }
    });
});
Activity icon

Replied to ReflectionException (-1) Class Post Does Not Exist

Maybe you made a great long shot. Take a look:

Psy Shell v0.9.9 (PHP 7.3.7 — cli) by Justin Hileman

>>> $category = new Category
[!] Aliasing 'Category' to 'App\Category' for this Tinker session.
=> App\Category {#3014}

>>> $post = new Post
[!] Aliasing 'Post' to 'App\Http\Resources\Post' for this Tinker session.
TypeError: Too few arguments to function Illuminate/Http/Resources/Json/JsonResource::__construct(), 0 passed in Psy Shell code on line 1 and exactly 1 expected

>>> $post = new App\Post
=> App\Post {#3023}

>>> resolve(App\Post::class);
=> App\Post {#3008}

use App\Post solved the problem in tinker:

>>> use App\Post;
>>> Post::first()
=> App\Post {#3028
     id: 1,
     user_id: 1,
     category_id: 5,
     created_at: "2019-08-07 15:53:32",
     updated_at: "2019-08-07 15:53:32",
     displayed_at: null,
     comment_authorized: 1,
     title: "azeazeazezaeazeazeazeazeazeaezae",
     content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu eros accumsan, vestibulum turpis et, eleifend dolor. Nam sed consequat nunc. In non dolor at diam venenatis mattis ut ac sapien. Integer et imperdiet neque, vitae fringilla mi. Quisque fringilla, massa eget vestibulum volutpat, mi odio ultrices nisl, sit amet sodales felis eros at elit. Aenean mattis tortor scelerisque iaculis viverra. Phasellus tincidunt tellus et dolor dictum, et vulputate urna efficitur. Phasellus quis risus et libero pellentesque venenatis eget vel est. Etiam ornare venenatis odio, ut tempus nisi aliquam malesuada. Fusce ultrices vulputate lorem, vel porttitor eros. In tortor lorem, auctor et augue finibus, mollis blandit enim. Nam nec massa lorem. Integer pulvinar consequat odio viverra maximus. Suspendisse potenti. Aenean ut condimentum magna.",
   }

But the problem isn't the service provider because I don't even know what this file is used for, so I never opened it:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

My post resource file is also clean as it was at his creation (looked at it when tinker said "Too few arguments [...] JsonResource::__construct()[...]:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Post extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

I also tried another dump-autoload:

C:\xampp\htdocs\qaa>composer dump-autoload
Generating optimized autoload files> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-debugbar
Discovered Package: beyondcode/laravel-dump-server
Discovered Package: fideloper/proxy
Discovered Package: kris/laravel-form-builder
Discovered Package: laravel/tinker
Discovered Package: laravelcollective/html
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
Generated optimized autoload files containing 3782 classes

C:\xampp\htdocs\qaa>php artisan config:clear
Configuration cache cleared!

C:\xampp\htdocs\qaa>php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.7 — cli) by Justin Hileman
>>> $post = new Post
[!] Aliasing 'Post' to 'App\Http\Resources\Post' for this Tinker session.
TypeError: Too few arguments to function Illuminate/Http/Resources/Json/JsonResource::__construct(), 0 passed in Psy Shell code on line 1 and exactly 1 expected
>>> $post = new App\Post
=> App\Post {#3016}
>>> $category = new Category
[!] Aliasing 'Category' to 'App\Category' for this Tinker session.
=> App\Category {#3008}
Activity icon

Replied to How To Dry Up This Part Of My Code?

Well.

As I see all your code is exactly the same except the ID in your html page.

Just set the same ID #myForm instead of #createForm and #updateForm and #errors instead of #createErrors and #updateErrors and you can call the same Ajax function with two forms.

Then you can create a submit-form.js and include it in your two html pages.

<script type="text/javascript">
    $("#myForm").submit(function(e) {
        e.preventDefault();
        var form = $(this);
        var url = form.attr('action');
        $.ajax({
            type: "POST",
            url: url,
            data: $('#myForm').serialize(),
            success: function(data)
            {
                if(data=="success")
                {
                    location.reload();
                }
                else
                {
                    var html = "<ul>";
                    for(var dat in data)
                    {
                        for (var x in data[dat])
                        {
                            html = html+"<li>"+data[dat][x]+"</li>";
                        }
                    }
                    html = html+"</ul>";
                    $("#errors").attr("class","alert alert-danger");
                    $("#errors").html(html);
                }
            }
        });
    });
</script>
Aug
08
3 months ago
Activity icon

Replied to ReflectionException (-1) Class Post Does Not Exist

@eslamahmed > Already tried, and once again right now: no effect.

@talinon > I will have got a PostController outside of "AdminZone" which will uses only index and show method to display the blog posts. But, it's in a different namespace and for now, I don't have created it yet. The long shot was a good shot but not for now... For now, only routes is declared:

|        | GET|HEAD  | admin/post                     | admin::post.index       | App\Http\Controllers\AdminZone\[email protected]           | web,auth                                             |
|        | POST      | admin/post                     | admin::post.store       | App\Http\Controllers\AdminZone\[email protected]           | web,auth                                             |
|        | GET|HEAD  | admin/post/create              | admin::post.create      | App\Http\Controllers\AdminZone\[email protected]          | web,auth                                             |
|        | GET|HEAD  | admin/post/{post}              | admin::post.show        | App\Http\Controllers\AdminZone\[email protected]            | web,auth                                             |
|        | PUT|PATCH | admin/post/{post}              | admin::post.update      | App\Http\Controllers\AdminZone\[email protected]          | web,auth                                             |
|        | DELETE    | admin/post/{post}              | admin::post.destroy     | App\Http\Controllers\AdminZone\[email protected]         | web,auth                                             |
|        | GET|HEAD  | admin/post/{post}/edit         | admin::post.edit        | App\Http\Controllers\AdminZone\[email protected]            | web,auth                                             |
|        | GET|HEAD  | post                           | post.index              | App\Http\Controllers\[email protected]                     | web                                                  |
|        | GET|HEAD  | post/{post}                    | post.show               | App\Http\Controllers\[email protected]                      | web

This is my entire stacktrace, hope this is what you're expecting for (new into Laravel):


58
ReflectionException 
…\vendor\laravel\framework\src\Illuminate\Container\Container.php790
57
ReflectionClass __construct
…\vendor\laravel\framework\src\Illuminate\Container\Container.php790
56
Illuminate\Container\Container build
…\vendor\laravel\framework\src\Illuminate\Container\Container.php667
55
Illuminate\Container\Container resolve
…\vendor\laravel\framework\src\Illuminate\Container\Container.php615
54
Illuminate\Container\Container make
…\vendor\laravel\framework\src\Illuminate\Foundation\Application.php767
53
Illuminate\Foundation\Application make
…\vendor\laravel\framework\src\Illuminate\Routing\RouteBinding.php66
52
Illuminate\Routing\RouteBinding Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php802
51
 call_user_func
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php802
50
Illuminate\Routing\Router performBinding
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php770
49
Illuminate\Routing\Router substituteBindings
…\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php37
48
Illuminate\Routing\Middleware\SubstituteBindings handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
47
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
46
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php43
45
Illuminate\Auth\Middleware\Authenticate handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
44
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
43
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php75
42
Illuminate\Foundation\Http\Middleware\VerifyCsrfToken handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
41
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
40
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php49
39
Illuminate\View\Middleware\ShareErrorsFromSession handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
38
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
37
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php56
36
Illuminate\Session\Middleware\StartSession handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
35
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
34
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php37
33
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
32
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
31
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php66
30
Illuminate\Cookie\Middleware\EncryptCookies handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
29
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
28
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php104
27
Illuminate\Pipeline\Pipeline then
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php682
26
Illuminate\Routing\Router runRouteWithinStack
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php657
25
Illuminate\Routing\Router runRoute
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php623
24
Illuminate\Routing\Router dispatchToRoute
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php612
23
Illuminate\Routing\Router dispatch
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php176
22
Illuminate\Foundation\Http\Kernel Illuminate\Foundation\Http\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php30
21
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\barryvdh\laravel-debugbar\src\Middleware\InjectDebugbar.php65
20
Barryvdh\Debugbar\Middleware\InjectDebugbar handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
19
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
18
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\fideloper\proxy\src\TrustProxies.php57
17
Fideloper\Proxy\TrustProxies handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
16
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
15
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php21
14
Illuminate\Foundation\Http\Middleware\TransformsRequest handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
13
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
12
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php21
11
Illuminate\Foundation\Http\Middleware\TransformsRequest handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
10
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
9
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php27
8
Illuminate\Foundation\Http\Middleware\ValidatePostSize handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
7
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
6
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php62
5
Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode handle
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php163
4
Illuminate\Pipeline\Pipeline Illuminate\Pipeline\{closure}
…\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php53
3
Illuminate\Routing\Pipeline Illuminate\Routing\{closure}
…\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php104
2
Illuminate\Pipeline\Pipeline then
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php151
1
Illuminate\Foundation\Http\Kernel sendRequestThroughRouter
…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php116
0
Illuminate\Foundation\Http\Kernel handle
…\public\index.php55
Activity icon

Replied to Prevent Multiple User Editing The Same Resource

Just a suggestion, maybe not what you want:

With a field "open_elsewhere" nullable-timestamp in table:

In [email protected] method

if open_elsewhere is not null and recently opened (manage this variable) > Sorry, you cannot edit this resource

else update line in table to set open_elsewhere at current_timestamp and return form view to edit

In [email protected] method:

update line in table with open_elsewhere to null

Activity icon

Started a new Conversation ReflectionException (-1) Class Post Does Not Exist

Hi. Got a headache...

I've just created all admin pages for "category" resource of a blog website. Everything is okay.

I tried to do exactly the same structure to manage "post" resource. [email protected], create and store is okay.

But now i'm trying to do the edit and i got a: ReflectionException (-1) Class Post does not exist The error occurs even on destroy function call.

I past few hours trying to search over the web (event in this forum), tried artisan config:cache, composer dumpautoload -o (also without -o ), verified my Post class doesn't have any syntax error, check composer.json autoload. Nothing worked! My composer.json:

    "autoload": {
        "psr-4": {
            "App\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },

My Post class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded = [];
    
    public function comments()
    {
        return $this->hasMany('Comment');
    }
    
    public function author()
    {
        return $this->belongsTo('User');
    }
    
    public function category()
    {
        return $this->belongsTo('Category');
    }
}

My PostController:

<?php

namespace App\Http\Controllers\AdminZone;

use App\Post;
use App\Category;
use Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\PostStoreUpdateRequest;

class PostController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  Post  $post
     * @return \Illuminate\Http\Response
     */
    public function edit(Post $post)
    {
        $categories = Category::pluck('name', 'id');
        return view('admin.post.edit')->with('post', $post)->with('categories', $categories);
    }
// And some other code for other actions

My route:list for post:

GET|HEAD  | admin/post                     | admin::post.index       | App\Http\Controllers\AdminZone\[email protected]           | web,auth                                             |
|        | POST      | admin/post                     | admin::post.store       | App\Http\Controllers\AdminZone\[email protected]           | web,auth                                             |
|        | GET|HEAD  | admin/post/create              | admin::post.create      | App\Http\Controllers\AdminZone\[email protected]          | web,auth                                             |
|        | GET|HEAD  | admin/post/{post}              | admin::post.show        | App\Http\Controllers\AdminZone\[email protected]            | web,auth                                             |
|        | PUT|PATCH | admin/post/{post}              | admin::post.update      | App\Http\Controllers\AdminZone\[email protected]          | web,auth                                             |
|        | DELETE    | admin/post/{post}              | admin::post.destroy     | App\Http\Controllers\AdminZone\[email protected]         | web,auth                                             |
|        | GET|HEAD  | admin/post/{post}/edit         | admin::post.edit        | App\Http\Controllers\AdminZone\[email protected]            | web,auth                                             |

Does someone see anything wrong??

Activity icon

Replied to How Can I Use Two Different Template For Same Route In Laravel

SEO bots aren't logged users.

They will only see the guest views.

Activity icon

Replied to How Can I Use Two Different Template For Same Route In Laravel

https://laravel.com/docs/5.8/authentication#protecting-routes

You should use an auth middleware in your web.php, for example:

// public routes
Route::resource('post', 'PostController', array('only' => array('index', 'show')));

// Logged user only routes
Route::resource('post', 'PostController')->middleware('auth');
Aug
07
3 months ago
Activity icon

Replied to Relation Between Same Users Table

https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

In Laravel Documentation, it says:

Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.

Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method:

return $this->hasMany('App\Comment', 'foreign_key');

In your case it's the same table, so Laravel is searching a "user_id" inside the user table > There is not.

Add a coach_id column which you fill when a coach is selected(nullable if runner doesn't have one) and specify the coach user id inside of it. Then declare it in your belongsTo and hasMany methods:

class User extends Authenticatable
{
    public function coach() // Return Coach
    {
        return $this->belongsTo('App\User', 'coach_id');
    }

    public function runners() // Return User
    {
        return $this->hasMany('App\User', 'coach_id');
    }
}
Activity icon

Replied to Store And Update Request Are The Same Except The Unique Id. A Way To Merge?

Well, I'm not very sure this is a good way to do. Assuming I add a segment /admin to my panel (which is the case): your conditions is always true.

So if I create my entire project with this rules and no /admin segment.

And then I say to myself "Hmmm, maybe I should add /admin segment" > All my /admin rules crash.

I think catching the HTTP method() is more sure.

Activity icon

Replied to Store And Update Request Are The Same Except The Unique Id. A Way To Merge?

Your tip for sure is great when rules became more complicated, I'll probably use this way in future. In this case, they are very short and easily readable/supportable.

To check if I fully understand what you mean. You do something like that?

public function rules()
{
    if ($this->method() == 'PATCH') return $this->updateRules();
    else return $this->createRules();
}

protected function createRules() {
         return [
        'name' => 'required|string|max:50|unique:categories,name',
        'parent_id' => 'nullable'
    ];
}

protected function updateRules() {
         return [
        'name' => 'required|string|max:50|unique:categories,name,'.$this->category->id,
        'parent_id' => 'nullable'
    ];
}