Laravel - find by custom column or fail

后端 未结 2 1978
梦如初夏
梦如初夏 2021-02-01 12:01

There\'s findOrFail() method which throws 404 if nothing was found, e.g.:

User::findOrFail(1);
相关标签:
2条回答
  • 2021-02-01 12:32

    Update: I'm currently using Laravel 6.9.0 and I confirm that @jeff-puckett is right. Where clause works fine. This is how it works on my tinker.

    >>> \App\Models\User::findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
    >>> App\Models\User
         id: "123b5545-5adc-4c59-9a27-00d035c1d212",
         name: "John",
         surname: "Graham",
         email: "john.graham@test.com",
         email_verified_at: "2020-01-03 16:01:53",
         created_at: "2020-01-03 16:01:59",
         updated_at: "2020-01-03 16:01:59",
         deleted_at: null,
    
    >>> \App\Models\User::where('name', 'Buraco')->findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
    >>> Illuminate/Database/Eloquent/ModelNotFoundException with message 'No query results for model [App/Models/User] 123b5545-5adc-4c59-9a27-00d035c1d212'
    
    
    >>> \App\Models\User::where('name', 'John')->findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
    >>> App\Models\User
         id: "123b5545-5adc-4c59-9a27-00d035c1d212",
         name: "John",
         surname: "Graham",
         email: "john.graham@test.com",
         email_verified_at: "2020-01-03 16:01:53",
         created_at: "2020-01-03 16:01:59",
         updated_at: "2020-01-03 16:01:59",
         deleted_at: null,
    

    Outdated:
    It took at least two hours to realize that if you chain firstOrFail() method after where() in Laravel 5.6, it basically tries to retrieve the first record of the table and removes where clauses. So call firstOrFail before where.

    Model::firstOrFail()->where('something', $value)
    
    0 讨论(0)
  • 2021-02-01 12:42

    Try it like this:

    Page::where('slug', '=', 'about')->firstOrFail();
    
    0 讨论(0)
提交回复
热议问题