Breaking Posts

6/trending/recent
Type Here to Get Search Results !

Laravel important code




For find(n), you retrieve a row based on the primary key which is 'n'.

For first(), you retrieve the first row among all rows that fit the where clauses.

For get(), you retrieve all the rows that fit the where clauses. (Please note that loops are required to access all the rows or you will get some errors).


find returns one row from the database and represent it as a fluent / eloquent object. e.g. SELECT * FROM users WHERE id = 3 is equivalent to DB::table('users')->find(3);



When I want all data from a table I use the all() method


Model::all();


The get() method will give you all the values from the database that meet your parameters where as first() gets you just the first result. You use find() and findOrFail() when you are searching for a key. This is how I use them:




When I want to find by the primary key:


  Model::find(1)->first();



   Model::findOrFail(1)->first();


   Model::where('field', '=', 'value')->get();




When I am looking for specific data as in a where clause:


Model::where('field', '=', 'value')->get();



When I want only the first value of the data in the where clause.


Model::where('field', '=', 'value')->first();






#

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');


#So, your user has passport, right? Then, in your user Model you need to write the following method to manage this relationship:


public function passport(){

    return $this->hasOne(Passport::class, 'username', 'username');


    ->one to one realation in laravel model code 

  #So, your user has passport, right? Then, in your user Model 

  #you need to write the following method to manage this relationship:

  #first parameter is the passport model and second is the foregn key ,the is local key

  ---------------------------------------------------------------------------------------------


public function passport(){

    return $this->hasOne(Passport::class, 'username', 'username');





#

/** Add this to your Profile table migration or create a new migration */

$table->foreignId('user_id');




#

public function profile(): HasOne

{

    return $this->hasOne(Profile::class);

}











#

public function user(): BelongsTo

{

    return $this->belongsTo(User::class, 'author_id'); // Omit the second parameter if you're following convention

}




#

$profile = $user->profile;

$name = $user->profile->display_name;




#$user = Profile::find(1)->user;






#


$posts = Profile::find(1)->posts;

// $posts = Profile::find(1)->posts()->get();

 

foreach ($posts as post) {

   // Do something

}

 

$lastPost = Profile::find(1)->posts()->latest()->first();











HasOneThrough and HasManyThrough

Now that we've seen those examples, let's go one step further. Now we want to define a relationship through an other model.


Consider our example above, where each User has one Profile, and where each Profile has many Posts. An example of a relationship through an other model is that we want to get all posts for a user. We can't directly add a hasMany(Post::class) relationship on our User model, because the Post model doesn't contain a user_id, it only has a profile_id. This is a perfect example of a has many through relationship.


To define such a relationship, you can do it very similar to what we saw above. In our example, add the following to the User model:


public function posts(): HasManyThrough

{

    return $this->hasManyThrough(Post::class, Profile::class);

}


php artisan make:controller admin/RelationsipController


#make controller inside a folder

php artisan make:controller admin/RelationsipController



# create all    

php artisan make:model Todo -all


Other Options


-c, --controller Create a new controller for the model


-f, --factory Create a new factory for the model


--force Create the class even if the model already exists


-m, --migration Create a new migration file for the model


-s, --seed Create a new seeder file for the model


-p, --pivot Indicates if the generated model should be a custom intermediate table model


-r, --resource Indicates if the generated controller should be a resource controller


For More Help




#realationship

<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;


class Student extends Model

{

    use HasFactory;


    // public function Cource(){

    //     return $this->hasOne(Cource::class);

    //     // return $this->hasOne(Cource::class, 'username', 'username');

    // }


    public function Cource()

    {

        return $this->hasOne('App\Models\Cource');

    }

}




#

<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;


class Cource extends Model

{

    use HasFactory;



//     public function Student(): BelongsTo

// {

//     return $this->belongsTo(Student::class); // Omit the second parameter if you're following convention

// }

public function Student()

{

    return $this->belongsTo('App\Models\Student');

}


}



#

  public function index()

    {





//   return $cource = Student::find(3)->cource;



  

     return $student = Cource::find(4)->student;

  


     return view('admin.relationship');

    }




https://twitter.com/DevPritam5

https://www.facebook.com/profile.php?id=100088503347257

https://www.instagram.com/devpritam2020/





#image form public folder

{{ URL::to('/') }}/images/stackoverflow.png



<img src="{{url('/images/myimage.jpg')}}" alt="Image"/>


<img src={{url('/images/photo.type')}} width="" height="" alt=""/>


<img style="border-radius: 50%;height: 50px;width: 80px;"  src="<?php echo asset("storage/TeacherImages/{$teacher->profilePic}")?>">



{{ URL::to('/'}}/folder name of the stored files inside public folder Laravel/'.$variable->filename

For Example:-   {{ URL::to('/'}}/images/$value->product_image





In this case, you can retrieve the image or file from the public folder only as shown below

{{ URL::to('/'}}/'.$variable->filename






{{asset('/'.$variable->filename)}}




--------------------------

#laravel validatoin in controller


 $this->validate($request,[

         'username'=>'required|max:8',

         'password'=>'required'


      ]);   




   public function store(Request $request)

{

    $validated = $request->validate([

        'title' => 'required|unique:posts|max:255',

        'body' => 'required',

    ]);

 

    // The blog post is valid...

}



#old value inlaravel form 


<input type="text" name="title" value="{{ old('title') }}">





#host larvel project index file 


require __DIR__.'/../bootstrap/autoload.php';


#

But when I try to add a foreign key to migration it doesn't work


Here is my migration table


Copy Code

public function up()

{

    Schema::create('testimonials', function (Blueprint $table) {

        $table->id();

        $table->integer('test_cat_id');

        $table->string('name');

        $table->string('company');

        $table->string('position');

        $table->longText('details');

        $table->string('image');

        $table->timestamps();


        $table->foreign('test_cat_id')->references('id')->on('testimonial_categories')->onDelete('cascade');

    });

}


#

whats the error showing .....


try this


Copy Code

$table->foreignId('test_cat_id')->constrained('testimonial_categories')->cascadeOnDelete();


#

Change it to big integer, because id column by default is big integer as well.


Copy Code

$table->bigInteger('test_cat_id');




#

Schema::table('admins', function (Blueprint $table) {

    $table->dropForeign('admins_post_id_foreign');

    $table->dropColumn('post_id');

});




#get relatin view 


$posts = Post::with('comments')->all();


return view('myview', compact('posts'));



------------

@foreach($posts as $post)


    // Display post information


    @if (count($post->comments))

        @foreach($post->comments as $comment)

            // Display comment information

        @endforeach

    @else 

        No comments Found

    @endif  


@endforeach



  @foreach($students as $student)

                    <tbody>

                      <tr>

                        <th scope="row">1</th>

                        <td> {{  $student->student_name }}</td>

                      </tr>

                     

                      

                    </tbody>

                    @endforeach


#

  return $query->orderBy('view_count','desc');




  #

    public function index()

    {

        $posts = Post::with('category','author')->latest()->paginate($this->limit);

        $postCount = Post::count();

        return view("backend.blog.index", compact('posts','postCount'));

    }



    #

          return $childcource = Cource::whereHas('childcourcebycource')->get();



childcources



#

https://stackoverflow.com/questions/24913348/display-an-array-in-a-blade-template-from-laravel




#  array of an array 

foreach($outerArray as $key => $array) {

       foreach($array as $key1 => $value) {

          $array[$key1]['sku_id'] = 'XYZ';

       }

    }





    #



/* foreach example 4: multi-dimensional arrays */

$a = array();

$a[0][0] = "a";

$a[0][1] = "b";

$a[1][0] = "y";

$a[1][1] = "z";


foreach ($a as $v1) {

    foreach ($v1 as $v2) {

        echo "$v2\n";

    }

}



#

<?php 

$freelancer = array( 

    "name" => "Eric", 

    "email" => "Eric@gmail.com", 

    "age" => 22, 

    "gender" => "male"

); 

  

// Loop through employee array 

foreach($freelancer as $key => $value) { 

    echo $key . ": " . $value . "<br>"; 

?>


name: Eric

email: Eric@gmail.com

age: 22

gender: male











#important code for 28-12-2022


return view('Tracks.index')->with(["tracks" => $tracks]);




@foreach($tracks AS $track)

  {{ $track->comments }}

  @foreach($track->trials AS $trial)

    {{ $trial->code }}

    @foreach($trial->samples AS $sample)

      {{ $sample->variety }}

    @endforeach

  @endforeach

@endforeach




https://www.appsloveworld.com/laravel/100/121/how-to-show-nested-array-with-blade-in-laravel-5-1



#

@foreach($data as $date => $dailyData)

    <tr>

        <td>{{$date}}</td>

        @foreach($dailyData as $key => $value)

            <td>

                <span>{{$key}}</span>

                <strong>{{$value}}</strong>

            </td>

        @endforeach

    </tr>

@endforeach




#

$this->savedTimers = TimeLog::where('id',23)

        ->join('projects', 'projects.id', '=', time_logs.project_id')

        ->select('projects.project_name', 'time_logs.*')

        ->orderBy('created_at','desc')

        ->get();

$this->savedTimers = $savedData->groupBy('project_id')->all();











#

@foreach($tracks AS $track)

  {{ $track->comments }}

  @foreach($track->trials AS $trial)

    {{ $trial->code }}

    @foreach($trial->samples AS $sample)

      {{ $sample->variety }}

    @endforeach

  @endforeach

@endforeach

https://stackoverflow.com/questions/64206847/how-to-display-nested-array-data-in-laravel-blade






#delete foregn key relavent data if main is delted 

https://stackoverflow.com/questions/55677896/how-to-delete-a-foreign-key-constraint-in-laravel






<?php

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';


var_dump(json_decode($json));

var_dump(json_decode($json, true));


?>



r

object(stdClass)#1 (5) {

    ["a"] => int(1)

    ["b"] => int(2)

    ["c"] => int(3)

    ["d"] => int(4)

    ["e"] => int(5)

}


array(5) {

    ["a"] => int(1)

    ["b"] => int(2)

    ["c"] => int(3)

    ["d"] => int(4)

    ["e"] => int(5)

}









<?php

$parents = array([

    "Narbada prasad" => "35",

    "Gangu" => "37",

    "Dipak" => [

        "Tina" => "35",

        "sonali" => "35",

        "pari" =>[

            

            "ram" => "35",

            "shyam" => "35",

            "karan" => "35",

            

            ]

        

        

        

        ]

    

]);


foreach($parents as $key=> $parent )

{

     print_r($parent);

    

    

    

}


?>





Array

(

    [Narbada prasad] => 35

    [Gangu] => 37

    [Dipak] => Array

        (

            [Tina] => 35

            [sonali] => 35

            [pari] => Array

                (

                    [ram] => 35

                    [shyam] => 35

                    [karan] => 35

                )


        )


)









#Accessing array elements with square bracket syntax ¶

Array elements can be accessed using the array[key] syntax.


Example #7 Accessing array elements


<?php

$array = array(

    "foo" => "bar",

    42    => 24,

    "multi" => array(

         "dimensional" => array(

             "array" => "foo"

         )

    )

);


var_dump($array["foo"]);

var_dump($array[42]);

var_dump($array["multi"]["dimensional"]["array"]);

?>



#

<?php

$array = array(

    "foo" => "bar",

    42    => 24,

    "multi" => array(

         "dimensional" => array(

             "array" => "foo"

         )

    )

);


var_dump($array["foo"]);

var_dump($array[42]);

var_dump($array["multi"]["dimensional"]["array"]);

?>




#How to select specific columns in laravel eloquent


Table::select('name','surname')->where('id', 1)->get();



Table::where('id', 1)->get(['name','surname']);

    


#By using all() method we can select particular columns from table like as shown below.


ModelName::all('column1', 'column2', 'column3');



#

Model::where('id', 1)

         ->pluck('name', 'surname')

         ->all();



#

Also Model::all(['id'])->toArray() it will only fetch id as array.


#YouModelName::get(['id', 'name']);



#

$user = User::where('username', 'bobbyiliev')->get(['name']);


$user = User::where('username', 'bobbyiliev')->first(['name', 'age']);



#User::where('username', 'bobbyiliev')->first(['name'])->name;







Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.