1. Go to this page and download the library: Download movor/laravel-custom-casts library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
movor / laravel-custom-casts example snippets
// File: app/User.php
namespace App;
use App\CustomCasts\ImageCast;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Movor\LaravelCustomCasts\HasCustomCasts;
class User extends Authenticatable
{
use Notifiable, HasCustomCasts;
protected $fillable = [
'name', 'email', 'password', 'image'
];
protected $hidden = [
'password', 'remember_token'
];
protected $casts = [
'image' => ImageCast::class
];
}
// ...
// File: app/CustomCasts/ImageCast.php
namespace App\CustomCasts;
use Movor\LaravelCustomCasts\CustomCastBase;
use Illuminate\Http\UploadedFile;
class ImageCast extends CustomCastBase
{
public function setAttribute($file)
{
// Define storage folder
// (relative to "storage/app" folder in Laravel project)
// Don't forget to create it !!!
$storageDir = 'images';
// Generate random image name
$filename = str_random() . '.' . $file->extension();
// Save image to predefined folder
$file->storeAs($storageDir, $filename);
// This will be stored in db field: "image"
return $storageDir . '/' . $filename;
}
}
// File: app/Http/Controllers/UserController.php
// ...
protected function create(Request $request)
{
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
// Past the whole Illuminate\Http\UploadedFile object,
// we'll handle it in our ImageCast class
'image' => $request->file('image')
]);
}
// ...
// File: app/CustomCasts/ImageCast.php
// Add at the top
use Storage;
// ...
// This method will be triggered after model has been deleted
public function deleted()
{
// We can access underlying model with $this->model
// and attribute name that is being casted with $this->attribute
// Retrieve image path and delete it from the disk
$imagePath = $this->model->image;
Storage::delete($imagePath);
}
// ...
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.