first laravel code example
Example 1: laravel eloquent get first
$user = App\User::where('id',$id)->first();
$userId = App\User::where(...)->pluck('id');
Example 2: laravel create or update
$flight = App\Models\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
Example 3: laravel first or create
use App\Models\Flight;
$flight = Flight::firstOrCreate([
'name' => 'London to Paris'
]);
$flight = Flight::firstOrCreate(
['name' => 'London to Paris'],
['delayed' => 1, 'arrival_time' => '11:30']
);
$flight = Flight::firstOrNew([
'name' => 'London to Paris'
]);
$flight = Flight::firstOrNew(
['name' => 'Tokyo to Sydney'],
['delayed' => 1, 'arrival_time' => '11:30']
);
Example 4: larave Soft Deletes
Schema::table('flights', function (Blueprint $table) {
$table->softDeletes();
});
Example 5: laravel find query
return Destination::orderByDesc(
Flight::select('arrived_at')
->whereColumn('destination_id', 'destinations.id')
->orderBy('arrived_at', 'desc')
->limit(1)
)->get();
Example 6: eloquent firstOrCreate
firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.