how to make a new column without using migration - laravel

I need to make new columns in a table using the controller file. for doing this task I added some migration code in the controller as follows
use Illuminate\Support\Facades\Schema;
and put this inside a controller function
public function getColumn(Request $request)
{
$columnName = $request->columnName;
Schema::table('tablename', function($table)
{
$table->double(columnName)->nullable();
});
}
here I want to put a name that was I am getting from the request, I unable to put the $columnName inside this code

You need to pass the columnName Variable to the function.
Probably something like this:
public function getColumn(Request $request)
{
$columnName = $request->columnName;
Schema::table('tablename', function($table) use($columnName)
{
$table->double($columnName)->nullable();
});
}

Related

Laravel How can I configure "reserved_at" in the jobs table

I want to use Carbon::today()->addMonth() as default value of reserved_at column in jobs table
then I will use ite in the job in the way of
if(reserved_at == Carbon->today())
{
//execution
} else {
//don't
}
You can set reserved_at in model's creating event within the model boot() method, like that add following method in Job model:
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->reserved_at = Carbon::today()->addMonth();
});
}
It will append reserved_at field value in model when you storing data using eloquent methods.
Note: It'll not work with insert() query builder method.
I figured it out it's by using the function of the class InteractsWithQueue
->delay(Carbon::now()->addMinutes(5)) with the dispatch function

Laravel API: How to make a default image in a table instead of NULL

I am currently working on having a default image in a table instead of null. I already have an API that will put an image in that specific column (web_banner_profile) which is a POST method and a DELETE method that will make that column NULL, all of which using postman. I want to know how I can put a default image on all of the webinars table in the web_banner_profile.
This is the Banner Upload Controller:
<?php
namespace App\Http\Controllers;
use App\Models\Banner;
use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Validator;
class BannerUploadController extends Controller
{
public function FileUpload(Request $request, $id)
{
$uploaded_files = $request->file->store('public/uploads/');
$webinar = Banner::find($id);
$webinar->web_banner_profile = $request->file->hashName();
$results = $webinar->save();
if($results){
return ["result"=>"Image Added"];
}else{
return ["result"=>"Image Not Added"];
}
return ["result"=>"$uploaded_files"];
}
public function DeleteBanner($id)
{
$webinar = Banner::find($id);
if(is_null($webinar)){
return response()->json('Record not found!', 401);
}
$webinar->update(['web_banner_profile' => null]);
return response('Banner Deleted', 200);
}
}
This is the webinar table migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWebinarTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('webinar', function (Blueprint $table) {
$table->id();
$table->string('web_title');
$table->text('web_description');
$table->dateTime('web_start_date_time')->nullable();
$table->dateTime('web_end_date_time')->nullable();
$table->string('status')->nullable();
$table->string('remarks')->nullable();
$table->string('web_banner_profile')->nullable();
$table->bigInteger('created_by')->unsigned()->nullable();
$table->bigInteger('updated_by')->unsigned()->nullable();
$table->string('web_link')->nullable();
$table->timestamps();
});
Schema::table('webinar', function(Blueprint $table) {
$table->foreign('created_by')->references('id')->on('admins');
$table->foreign('updated_by')->references('id')->on('admins');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('webinar');
}
}
Any type of help/suggestion would be greatly appreciated. Thank you in advance!
I would consider using one of the Eloquent model events, specifically the created event. Something like the following:
class Webinar extends Model
{
protected static function booted()
{
static::created(function ($webinar) {
$webinar->update(['web_banner_profile' => 'your-image.jpg']);
});
}
}
Then whenever a new Webinar is created, the created event will be triggered and your default web_banner_profile value will be added to that record.
You don't have to hard code the value your-image.jpg, you could obtain it from a config of env file if you didn't want it in your code base to (arguably) make changing the value easier.

Eloquent: get changed columns

I need to log updated columns using Eloquent getChanges, It works just fine when use it in the same code context right after ex: updateOrCreate, but when call it from the "provider" it returns empty array, example of boot in service provider:
public function boot()
{
User::updating(function ($user) {
dd($user->getChanges()); //empty array
});
}
I get the problem I should use User::updated instead, ex:
public function boot()
{
User::updated(function ($user) {
dd($user->getChanges());
});
}

SQLSTATE[42S02]: Base table or view not found: 1146 error laravel

I have been trying to solve a problem for couple hours.
Basically I'm getting:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tp-laravel.image_location' doesn't exist (SQL: select location_id from image_location where image_id = 3) error.
Is this coming from a bad controller/model/migration? This is happening when I try to add an image in my website.
I have been trying to change stuff, add stuff and look on google a lot, but nothing solved it.
Image.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Image extends Model
{
protected $fillable = ['name'];
public function locations()
{
return $this->belongsToMany(Location::class);
}
public function getUpdatedAtAttribute($date)
{
return Carbon::parse($date)->locale('fr')->diffForHumans(Carbon::now());
}
}
Location.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
protected $fillable = ['name'];
public function locations()
{
return $this->belongsToMany(Image::class);
}
}
Here are the create and store methods from my controller:
public function create()
{
$locations = Location::pluck('name', 'id');
$users = User::pluck('name', 'id');
return view('posts.create', compact('locations'));
}
public function store(Request $request)
{
$image = Image::create(request()->all());
$image->locations()->sync(request()->get('locations'));
$user->users()->sync(request()->get('users'));
return redirect('/accueil');
}
And finally my image migration
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->BigInteger('location_id')->unsigned()->index();
$table->BigInteger('user_id')->unsigned()->index();
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('name', 100);
$table->timestamps();
});
When I press the create button in my view, the submit it's supposed to add the image in the database with user and location linked to it as a foreign key but the above error pops up.
Thanks!
The error is coming from
public function locations()
{
return $this->belongsToMany(Location::class);
}
Laravel assumes that you have intermediate table named alphabetically, for that is image_location and this table does not exist on your database.
The only way is to create such table, or if you have created the table with different name you can pass second parameter as table name. So it became:
public function locations()
{
return $this->belongsToMany(Location::class, 'TABLE_NAME');
}

Laravel How not to Rewrite the Same code again

I have a model, called Tours and controller ToursController which uses restful methods (index, show, store, edit, update etc).
Now I have this code:
$names = request()->get('names');
$lastnames = request()->get('lastnames');
$hotels = request()->get('hotel');
both in Store and Update. So i duplicate the same code twice. And this is only one exmaple of duplicated code.
I want to create a function "getEverythingFromRequest()"
which I can use in both Store and Update methods. Something like:
public function store (Request $request) {
getEverythingFromRequest();
dd($names[3];
}
public function store (Request $request) {
getEverythingFromRequest();
dd($hotels[2];
}
How can I do it? Globally, how can I avoid re-writing the same code in Controller?
There are a bunch of ways to solve this. One way would be to create a repo that extracts the arrays from your request. (I updated my code to use injection).
Controller
public function store (GuestsRepository $repo, Request $request) {
dd($repo->names);
}
Repository
<?php
namespace App;
class GuestsRepository
{
public $names;
public $lastnames;
public $hotels;
public function __construct(){
$this->names = request()->get('names');
$this->lastnames = request()->get('lastnames');
$this->hotels = request()->get('hotel');
}
}

Resources